mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 12:28:40 +00:00
Merge upstream PC input and dual-screen updates
This commit is contained in:
commit
68b0396dfe
819 files changed
+43953
-6186
No files matched your search
@@ -17,7 +17,8 @@ class App : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
com.droiddeck.launcher.ui.Themes.loadGradient(this)
|
||||
// Helper processes must not initialize the main USB provider or guest graphics context.
|
||||
com.droiddeck.launcher.ui.BuildWatermark.install(this)
|
||||
HomeApp.trackRecents(this)
|
||||
val process = if (android.os.Build.VERSION.SDK_INT >= 28) Application.getProcessName()
|
||||
else (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)
|
||||
.runningAppProcesses?.firstOrNull { it.pid == android.os.Process.myPid() }?.processName
|
||||
@@ -30,12 +31,13 @@ class App : Application() {
|
||||
return
|
||||
}
|
||||
if (process == "$packageName:xcloudnative") {
|
||||
// The native cloud player: the stores log and nothing that touches the Linux session.
|
||||
com.droiddeck.launcher.stores.StoresState.init(this)
|
||||
return
|
||||
}
|
||||
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic") return
|
||||
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic" ||
|
||||
process == "$packageName:shortcuts_sync" || process == "$packageName:bottom_desktop") return
|
||||
CrashHandler.install(this)
|
||||
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
|
||||
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
||||
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
|
||||
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
||||
@@ -53,11 +55,12 @@ class App : Application() {
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.epic.EpicBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gamejolt.GameJoltBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
|
||||
com.droiddeck.launcher.sync.Syncthing.init(this)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
|
||||
}
|
||||
|
||||
/** Fetches the packs an existing setup already relies on, so the first use after an update does not wait. */
|
||||
private fun prefetchAddonPacks() {
|
||||
val app = this
|
||||
Thread({
|
||||
|
||||
@@ -65,7 +65,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
}
|
||||
|
||||
fun state() = GpuDriversState(
|
||||
gpuName = gpu.displayName(activity), gpuFamily = gpu.family.label(activity), soc = gpu.soc, supportText = gpu.supportText(activity),
|
||||
gpuName = gpu.displayName(activity), gpuFamily = gpu.family.label(activity), soc = gpu.soc, supportText = gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)),
|
||||
supported = gpu.support == GpuInfo.Support.TESTED, unsupported = gpu.support == GpuInfo.Support.UNSUPPORTED,
|
||||
auto = mode == SessionPrefs.GPU_DRIVERS_AUTO, pairs = pairRows, busy = pairBusy, percent = pairPercent,
|
||||
autoStatus = autoStatus, releaseStatus = releaseStatus.ifEmpty { activity.getString(R.string.drivers_not_checked) }, checking = releaseChecking,
|
||||
@@ -264,7 +264,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
return
|
||||
}
|
||||
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
|
||||
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity).lowercase())
|
||||
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)).lowercase())
|
||||
return
|
||||
}
|
||||
releaseChecking = true
|
||||
|
||||
@@ -78,6 +78,7 @@ import com.droiddeck.launcher.session.SessionArtifacts
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SteamLibraries
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplays
|
||||
|
||||
@@ -161,6 +162,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var gameCores by mutableStateOf<Set<Int>>(emptySet())
|
||||
private var tuSysmem by mutableStateOf(false)
|
||||
private var zinkLazy by mutableStateOf(false)
|
||||
private var vkBridge by mutableStateOf(false)
|
||||
private var vkBridgeSafe by mutableStateOf(true)
|
||||
private var bridgeProtonDxvk by mutableStateOf(false)
|
||||
private val adrenoGpu by lazy { com.droiddeck.launcher.core.DeviceSupport.adreno() }
|
||||
private var noXalia by mutableStateOf(true)
|
||||
private var fastSync by mutableStateOf(false)
|
||||
private var syncFallback by mutableStateOf(true)
|
||||
@@ -194,7 +199,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var navRequest by mutableStateOf<String?>(null)
|
||||
private var storesShowMature by mutableStateOf(false)
|
||||
private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first())
|
||||
private var storesView by mutableStateOf(SessionPrefs.STORES_VIEWS.first())
|
||||
private var storesView by mutableStateOf(SessionPrefs.DEFAULT_STORES_VIEW)
|
||||
private var mic by mutableStateOf(false)
|
||||
private var wifiDiscovery by mutableStateOf(false)
|
||||
private var wifiDiscoveryPermission by mutableStateOf(false)
|
||||
@@ -315,15 +320,11 @@ class FrontEndActivity : ComponentActivity() {
|
||||
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.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else offerHomeScreen()
|
||||
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)
|
||||
SteamIntegration.setShortcutsListed(this, true)
|
||||
integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -456,7 +457,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var fexPreset by mutableStateOf("")
|
||||
private var forceSsbs by mutableStateOf(false)
|
||||
private var steamClientArch by mutableStateOf("arm64")
|
||||
private var runSteamAtStartup by mutableStateOf(false)
|
||||
private var startupSession by mutableStateOf(SessionPrefs.STARTUP_OFF)
|
||||
private var bootMovie by mutableStateOf(com.droiddeck.launcher.session.BootMovie.DROIDDECK_30)
|
||||
private var bootMovieSound by mutableStateOf(true)
|
||||
private var bootMovieCustomName by mutableStateOf<String?>(null)
|
||||
@@ -472,6 +473,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
||||
private var steamDownloadsInBackground by mutableStateOf(false)
|
||||
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
||||
private var backHold by mutableStateOf(true)
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
private var gameStorage by mutableStateOf("")
|
||||
private var slowUsb by mutableStateOf<com.droiddeck.launcher.session.UsbLink.SlowDrive?>(null)
|
||||
@@ -489,6 +491,40 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) }
|
||||
}
|
||||
private var steamLibraries by mutableStateOf<List<SteamLibraries.Entry>>(emptyList())
|
||||
private var foundSteamLibraries by mutableStateOf<List<SteamLibraries.Found>>(emptyList())
|
||||
private var allFilesAccessMissing by mutableStateOf(false)
|
||||
private var steamLibraryScan = 0
|
||||
private val pickSteamLibrary = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
val path = if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data) else null
|
||||
if (path != null) addSteamLibrary(path)
|
||||
}
|
||||
|
||||
private fun addSteamLibrary(path: String) {
|
||||
Thread({
|
||||
val result = SteamLibraries.add(this, path)
|
||||
ui.post {
|
||||
steamLibraries = SteamLibraries.list(this)
|
||||
refreshFoundSteamLibraries()
|
||||
refresh()
|
||||
when {
|
||||
result is SteamLibraries.AddResult.Refused ->
|
||||
android.widget.Toast.makeText(this, getString(R.string.main_storage_not_usable, result.reason), android.widget.Toast.LENGTH_LONG).show()
|
||||
result is SteamLibraries.AddResult.Added && result.entry.path != path ->
|
||||
android.widget.Toast.makeText(this, getString(R.string.libraries_used_inner, result.entry.label), android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}, "steam-library-add").start()
|
||||
}
|
||||
|
||||
private fun refreshFoundSteamLibraries() {
|
||||
allFilesAccessMissing = com.droiddeck.launcher.files.AllFilesAccess.missing()
|
||||
val scan = ++steamLibraryScan
|
||||
Thread({
|
||||
val found = SteamLibraries.found(this)
|
||||
ui.post { if (scan == steamLibraryScan) foundSteamLibraries = found }
|
||||
}, "steam-library-scan").start()
|
||||
}
|
||||
private var romsDir by mutableStateOf<String?>(null)
|
||||
private var steamGames by mutableStateOf<List<Library.SteamGame>>(emptyList())
|
||||
private var steamGamesX64 by mutableStateOf(false)
|
||||
@@ -529,7 +565,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
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 dualScreenSessions by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
|
||||
private var dualScreenControls by mutableStateOf(true)
|
||||
private var launcherStarted = false
|
||||
private lateinit var displayManager: DisplayManager
|
||||
@@ -538,10 +574,25 @@ class FrontEndActivity : ComponentActivity() {
|
||||
override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onDisplayChanged(displayId: Int) = refreshSecondScreenDisplays()
|
||||
}
|
||||
private val bottomScreenListener: () -> Unit = { refreshSecondScreenDisplays() }
|
||||
private val secondScreenTouchListener = object : android.hardware.input.InputManager.InputDeviceListener {
|
||||
override fun onInputDeviceAdded(deviceId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onInputDeviceRemoved(deviceId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onInputDeviceChanged(deviceId: Int) = refreshSecondScreenDisplays()
|
||||
}
|
||||
|
||||
private val homeRoleRequest = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||
homeChoiceOpen = false
|
||||
HomeApp.releaseUnusedHomeEntry(this)
|
||||
refreshHomeAppState()
|
||||
}
|
||||
private val gameSpaceAdd = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||
homeChoiceOpen = false
|
||||
if (HomeApp.inGameSpace(this)) enableHomeScreen()
|
||||
else refreshHomeAppState()
|
||||
}
|
||||
private var homeChoiceOpen = false
|
||||
private var gameSpaceOffered = false
|
||||
|
||||
override fun startActivity(intent: Intent?) {
|
||||
val compat = protons.protonBusyId != null || ProtonExtras.installInProgress
|
||||
@@ -707,7 +758,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
LauncherIcon.set(this, style)
|
||||
launcherIcon = LauncherIcon.current(this)
|
||||
if (launcherIcon == before) return false
|
||||
// Android finishes activities started through the alias that was just disabled.
|
||||
startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
.setComponent(LauncherIcon.activity(this))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
|
||||
@@ -739,7 +789,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
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()
|
||||
@@ -942,9 +995,10 @@ 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()
|
||||
@@ -972,6 +1026,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
homeChoiceOpen = savedInstanceState?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
|
||||
gameSpaceOffered = savedInstanceState?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
|
||||
if (savedInstanceState == null) readIntegrationIntent(intent)
|
||||
readGameIntent(intent)
|
||||
gameSyncFolder = GameFileSync.folder(this)
|
||||
@@ -1027,6 +1083,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
FrontEndScreen(
|
||||
FrontEndState(
|
||||
installed = installed, ready = ready, available = available?.version, removalPending = removalPending, runtimeActionsBlocked = runtimeChangesBlocked(),
|
||||
vkBridge = vkBridge, vkBridgeSafe = vkBridgeSafe, bridgeProtonDxvk = bridgeProtonDxvk, adreno = adrenoGpu,
|
||||
shortcutPicker = shortcutPicker,
|
||||
shortcutLibraryScanning = shortcutLibraryScanning,
|
||||
gameSyncFolder = gameSyncFolder,
|
||||
@@ -1054,7 +1111,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
dualScreen = dualDisplayId >= 0 && com.droiddeck.launcher.ui.DualScreenPanel.available,
|
||||
dualScreenDevice = dualScreenDevice,
|
||||
dualScreenMode = dualScreenMode,
|
||||
dualScreenLauncher = dualScreenLauncher,
|
||||
dualScreenSessions = dualScreenSessions,
|
||||
dualScreenControls = dualScreenControls,
|
||||
packages = packageRows,
|
||||
packageCatalogLoading = catalogLoading,
|
||||
@@ -1175,6 +1232,15 @@ class FrontEndActivity : ComponentActivity() {
|
||||
onInstallPackage = { id -> installPackage(id) },
|
||||
onRemovePackage = { id -> removePackage(id) },
|
||||
onRuntime = { onRuntimeButton() },
|
||||
onVkBridge = { on ->
|
||||
SessionPrefs.setVkBridge(this, on); vkBridge = on
|
||||
if (!on) com.droiddeck.launcher.session.ComponentsManager.settleAutoDxvk(this)
|
||||
},
|
||||
onVkBridgeSafe = { on -> SessionPrefs.setVkBridgeSafe(this, on); vkBridgeSafe = on },
|
||||
onBridgeProtonDxvk = { on ->
|
||||
SessionPrefs.setBridgeProtonDxvk(this, on); bridgeProtonDxvk = on
|
||||
if (on) com.droiddeck.launcher.session.ComponentsManager.settleAutoDxvk(this)
|
||||
},
|
||||
onFrameGenPick = { mode ->
|
||||
FrameGen.set(this, mode)
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
@@ -1288,8 +1354,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
SessionPrefs.setDualScreenMode(this, mode)
|
||||
refreshSecondScreenDisplays()
|
||||
},
|
||||
onDualScreenLauncher = { on ->
|
||||
SessionPrefs.setDualScreenLauncher(this, on)
|
||||
onDualScreenSessions = { mode ->
|
||||
SessionPrefs.setDualScreenSessionMode(this, mode)
|
||||
refreshSecondScreenDisplays()
|
||||
},
|
||||
onDualScreenControls = { on ->
|
||||
@@ -1327,8 +1393,11 @@ class FrontEndActivity : ComponentActivity() {
|
||||
integrationState = readIntegration()
|
||||
},
|
||||
onHomeScreen = { on ->
|
||||
HomeApp.setHomeScreenEnabled(this, on)
|
||||
refreshHomeAppState()
|
||||
if (on && HomeApp.hasGameSpace(this)) offerHomeScreen()
|
||||
else {
|
||||
HomeApp.setHomeScreenEnabled(this, on)
|
||||
refreshHomeAppState()
|
||||
}
|
||||
},
|
||||
onAndroidApp = { app, displayId -> launchAndroidApp(app, displayId) },
|
||||
onBackActionsInverted = { inverted ->
|
||||
@@ -1493,7 +1562,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() }
|
||||
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled(cold = true) }
|
||||
else {
|
||||
restoreCompatLaunch(savedInstanceState)
|
||||
pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
|
||||
@@ -1536,9 +1605,14 @@ class FrontEndActivity : ComponentActivity() {
|
||||
startSteamAtStartupIfEnabled()
|
||||
}
|
||||
|
||||
private fun startSteamAtStartupIfEnabled() {
|
||||
if (intent.action != Intent.ACTION_MAIN) return
|
||||
if (SessionPrefs.runSteamAtStartup(this) && !isFinishing && !isDestroyed) startSteamSession()
|
||||
private fun startSteamAtStartupIfEnabled(cold: Boolean = false) {
|
||||
if (intent.action != Intent.ACTION_MAIN && !(cold && intent.action == null)) return
|
||||
if (isFinishing || isDestroyed) return
|
||||
when (SessionPrefs.startupSession(this)) {
|
||||
SessionPrefs.STARTUP_STEAM -> startSteamSession()
|
||||
SessionPrefs.STARTUP_DESKTOP -> startSession(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP))
|
||||
}
|
||||
}
|
||||
|
||||
private fun playSteam() {
|
||||
@@ -1560,9 +1634,28 @@ class FrontEndActivity : ComponentActivity() {
|
||||
startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr), steamSession = true)
|
||||
}
|
||||
|
||||
@Suppress("OVERRIDE_DEPRECATION")
|
||||
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
|
||||
val outside = com.droiddeck.launcher.ui.DualScreenPanel.shownOn >= 0 &&
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.opensOutside(packageName, intent.component?.packageName ?: intent.`package` ?: intent.resolveActivity(packageManager)?.packageName)
|
||||
if (outside) {
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true)
|
||||
window.decorView.postDelayed({ if (hasWindowFocus()) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) }, 1500)
|
||||
}
|
||||
try {
|
||||
super.startActivityForResult(intent, requestCode, options)
|
||||
} catch (e: RuntimeException) {
|
||||
if (outside) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) applyLauncherFullscreen()
|
||||
if (hasFocus) {
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
|
||||
applyLauncherFullscreen()
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyLauncherFullscreen() {
|
||||
@@ -1621,16 +1714,24 @@ class FrontEndActivity : ComponentActivity() {
|
||||
|
||||
override fun onPause() {
|
||||
compatLaunchVisible = false
|
||||
if (android.os.Build.VERSION.SDK_INT >= 29) com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, true)
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (!homeChoiceOpen) {
|
||||
HomeApp.releaseUnusedHomeEntry(this)
|
||||
refreshHomeAppState()
|
||||
}
|
||||
if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
|
||||
compatLaunchVisible = true
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, false)
|
||||
orientation = SessionPrefs.orientation(this)
|
||||
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
requestedOrientation = launcherOrientation
|
||||
SteamIntegration.syncShortcutsListing(this)
|
||||
refreshWifiDiscovery()
|
||||
com.droiddeck.launcher.stores.StoresState.refresh(this)
|
||||
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
|
||||
@@ -1682,6 +1783,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
addDataScheme("file")
|
||||
})
|
||||
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
|
||||
com.droiddeck.launcher.input.DualScreen.watchTaken(bottomScreenListener)
|
||||
getSystemService(android.hardware.input.InputManager::class.java)?.registerInputDeviceListener(secondScreenTouchListener, ui)
|
||||
launcherStarted = true
|
||||
refreshSecondScreenDisplays()
|
||||
getSystemService(android.content.pm.LauncherApps::class.java).registerCallback(packageCallback, ui)
|
||||
@@ -1697,6 +1800,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
super.onSaveInstanceState(outState)
|
||||
outState.putBoolean(STATE_HOME_CHOICE_OPEN, homeChoiceOpen)
|
||||
outState.putBoolean(STATE_GAME_SPACE_OFFERED, gameSpaceOffered)
|
||||
if (slowUsbNever) SessionPrefs.setSlowUsbWarningOff(this)
|
||||
saveCompatLaunch(outState)
|
||||
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
|
||||
@@ -1716,7 +1821,13 @@ class FrontEndActivity : ComponentActivity() {
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onRestart() {
|
||||
super.onRestart()
|
||||
homeChoiceOpen = false
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
if (!homeChoiceOpen) HomeApp.releaseUnusedHomeEntry(this)
|
||||
unregisterReceiver(wifiLocationReceiver)
|
||||
unregisterReceiver(mediaReceiver)
|
||||
getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback)
|
||||
@@ -1725,6 +1836,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
com.droiddeck.launcher.stores.StoresState.libraryListener = null
|
||||
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
|
||||
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
|
||||
com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener)
|
||||
getSystemService(android.hardware.input.InputManager::class.java)?.unregisterInputDeviceListener(secondScreenTouchListener)
|
||||
launcherStarted = false
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
|
||||
flood = null
|
||||
@@ -1758,15 +1871,14 @@ class FrontEndActivity : ComponentActivity() {
|
||||
|
||||
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)
|
||||
dualScreenSessions = SessionPrefs.dualScreenSessionMode(this)
|
||||
dualScreenControls = SessionPrefs.dualScreenSessionControls(this)
|
||||
val target = com.droiddeck.launcher.input.DualScreen.display(this, displayManager, ownDisplayId)
|
||||
dualDisplayId = if (dualScreenLauncher) target?.displayId ?: -1 else -1
|
||||
dualDisplayId = target?.displayId ?: -1
|
||||
syncDualPanel()
|
||||
}
|
||||
|
||||
@@ -1795,12 +1907,32 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun offerHomeScreen() {
|
||||
if (!gameSpaceOffered && HomeApp.hasGameSpace(this) && !HomeApp.inGameSpace(this)) {
|
||||
gameSpaceOffered = true
|
||||
val opened = runCatching { gameSpaceAdd.launch(HomeApp.gameSpaceAddIntent()) }.isSuccess
|
||||
if (opened) {
|
||||
homeChoiceOpen = true
|
||||
android.widget.Toast.makeText(this, R.string.setup_home_game_space_first, android.widget.Toast.LENGTH_LONG).show()
|
||||
return
|
||||
}
|
||||
}
|
||||
enableHomeScreen()
|
||||
}
|
||||
|
||||
private fun enableHomeScreen() {
|
||||
HomeApp.setHomeScreenEnabled(this, true)
|
||||
refreshHomeAppState()
|
||||
manageHomeApp()
|
||||
}
|
||||
|
||||
private fun manageHomeApp() {
|
||||
homeChoiceOpen = true
|
||||
val request = HomeApp.roleRequestIntent(this)
|
||||
if (request != null) {
|
||||
homeRoleRequest.launch(request)
|
||||
} else {
|
||||
HomeApp.openSystemHomeSettings(this)
|
||||
} else if (runCatching { homeRoleRequest.launch(HomeApp.settingsIntent()) }.isFailure) {
|
||||
homeChoiceOpen = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2066,6 +2198,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
unfoldedControls = if (mode == SessionService.MODE_STEAM) unfoldedControls else null,
|
||||
unfoldedControlsWithController = unfoldedControlsWithController,
|
||||
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
||||
backHold = backHold,
|
||||
backActionsInverted = backActionsInverted,
|
||||
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
|
||||
picturePosition = if (mode == SessionService.MODE_STEAM) picturePosition else null,
|
||||
@@ -2073,6 +2206,9 @@ class FrontEndActivity : ComponentActivity() {
|
||||
mic = if (mode == SessionService.MODE_STEAM) mic else null,
|
||||
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
|
||||
storageOptions = storageOptions,
|
||||
steamLibraries = steamLibraries,
|
||||
foundSteamLibraries = foundSteamLibraries,
|
||||
allFilesAccessMissing = allFilesAccessMissing,
|
||||
storageDiagnostics = mode == SessionService.MODE_STEAM && storageDiagnostics,
|
||||
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
|
||||
forceSsbs = forceSsbs,
|
||||
@@ -2083,7 +2219,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
steamRepairQueued = steamRepairQueued,
|
||||
mangoapp = mangoapp,
|
||||
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
|
||||
runSteamAtStartup = mode == SessionService.MODE_STEAM && runSteamAtStartup,
|
||||
startupSession = startupSession,
|
||||
bootMovie = if (mode == SessionService.MODE_STEAM) bootMovie else null,
|
||||
bootMovieSound = bootMovieSound,
|
||||
bootMovieCustomName = bootMovieCustomName,
|
||||
@@ -2118,6 +2254,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
SessionPrefs.setUnfoldedControlsWithController(this, on); unfoldedControlsWithController = on
|
||||
},
|
||||
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
||||
onBackHold = { on -> SessionPrefs.setBackHold(this, on); backHold = on },
|
||||
onBackActionsInverted = { inverted ->
|
||||
SessionPrefs.setBackActionsInverted(this, inverted)
|
||||
backActionsInverted = inverted
|
||||
@@ -2136,6 +2273,22 @@ class FrontEndActivity : ComponentActivity() {
|
||||
onPickGameStorageFolder = {
|
||||
pickGameStorage.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_pick_game_storage), gameStorage.ifEmpty { null }))
|
||||
},
|
||||
onAddSteamLibrary = {
|
||||
pickSteamLibrary.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.libraries_pick), null))
|
||||
},
|
||||
onAddFoundSteamLibrary = { path -> addSteamLibrary(path) },
|
||||
onAllowAllFilesAccess = { com.droiddeck.launcher.files.AllFilesAccess.open(this) },
|
||||
onRenameSteamLibrary = { id, label ->
|
||||
SteamLibraries.rename(this, id, label)
|
||||
steamLibraries = SteamLibraries.list(this)
|
||||
refresh()
|
||||
},
|
||||
onRemoveSteamLibrary = { id ->
|
||||
SteamLibraries.remove(this, id)
|
||||
steamLibraries = SteamLibraries.list(this)
|
||||
refresh()
|
||||
refreshFoundSteamLibraries()
|
||||
},
|
||||
onStorageDiagnostics = { on ->
|
||||
SessionPrefs.setStorageDiagnosticsEnabled(this, on)
|
||||
storageDiagnostics = on
|
||||
@@ -2159,9 +2312,9 @@ class FrontEndActivity : ComponentActivity() {
|
||||
onReturnAfterGame = { on -> SessionPrefs.setReturnAfterGame(this, on); returnAfterGame = on },
|
||||
onShaderPrecache = { on -> SessionPrefs.setShaderPrecache(this, on); shaderPrecache = on },
|
||||
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
|
||||
onRunSteamAtStartup = { on ->
|
||||
SessionPrefs.setRunSteamAtStartup(this, on)
|
||||
runSteamAtStartup = on
|
||||
onStartupSession = { id ->
|
||||
SessionPrefs.setStartupSession(this, id)
|
||||
startupSession = id
|
||||
},
|
||||
onBootMovie = { id -> com.droiddeck.launcher.session.BootMovie.select(this, id); loadBootMovie() },
|
||||
onBootMovieSound = { on -> SessionPrefs.setBootMovieSound(this, on); bootMovieSound = on },
|
||||
@@ -2352,7 +2505,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
returnAfterGame = SessionPrefs.returnAfterGame(this)
|
||||
loadShaderPrecache(mode)
|
||||
steamController = SessionPrefs.steamController(this)
|
||||
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
|
||||
startupSession = SessionPrefs.startupSession(this)
|
||||
loadBootMovie()
|
||||
hdrOn = SessionPrefs.hdr(this, mode)
|
||||
upscaler = SessionPrefs.upscaler(this)
|
||||
@@ -2362,6 +2515,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, mode)
|
||||
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
backHold = SessionPrefs.backHold(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
directAudio = SessionPrefs.directAudio(this)
|
||||
picturePosition = SessionPrefs.picturePosition(this)
|
||||
@@ -2369,6 +2523,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
mic = SessionPrefs.micEnabled(this)
|
||||
refreshWifiDiscovery()
|
||||
gameStorage = SessionPrefs.gameStorage(this)
|
||||
steamLibraries = SteamLibraries.list(this)
|
||||
if (mode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
|
||||
storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this)
|
||||
settingsMode = mode
|
||||
Thread({
|
||||
@@ -2399,6 +2555,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
SessionPrefs.setGameStorage(this, path, label)
|
||||
gameStorage = path
|
||||
checkUsbLink()
|
||||
if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
|
||||
}
|
||||
|
||||
private fun checkUsbLink() {
|
||||
@@ -2422,6 +2579,9 @@ class FrontEndActivity : ComponentActivity() {
|
||||
gameCores = CpuCores.parse(SessionPrefs.gameCpus(this)).ifEmpty { CpuCores.all.toSet() }
|
||||
tuSysmem = SessionPrefs.tuSysmem(this)
|
||||
zinkLazy = SessionPrefs.zinkLazy(this)
|
||||
vkBridge = SessionPrefs.vkBridge(this)
|
||||
vkBridgeSafe = SessionPrefs.vkBridgeSafe(this)
|
||||
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
|
||||
noXalia = SessionPrefs.noXalia(this)
|
||||
fastSync = SessionPrefs.fastSync(this)
|
||||
syncFallback = SessionPrefs.syncFallback(this)
|
||||
@@ -2443,7 +2603,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
!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"
|
||||
if (listX64 != steamGamesX64) {
|
||||
steamGamesX64 = listX64
|
||||
@@ -2459,6 +2618,9 @@ class FrontEndActivity : ComponentActivity() {
|
||||
offline = OfflineMode.enabled(this)
|
||||
installed = LinuxRuntimeInstaller.installedVersion(this)
|
||||
ready = LinuxRuntime.isInstalled(this)
|
||||
vkBridge = SessionPrefs.vkBridge(this)
|
||||
vkBridgeSafe = SessionPrefs.vkBridgeSafe(this)
|
||||
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
|
||||
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
|
||||
ui.post { autoUpdateRuntime() }
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
@@ -2503,7 +2665,7 @@ 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 }
|
||||
@@ -2563,7 +2725,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
Thread({ checkCatalog() }, "catalog").start()
|
||||
return
|
||||
}
|
||||
if (installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()) { showNonAdreno = release; return }
|
||||
if (installed == null && !com.droiddeck.launcher.core.DeviceSupport.canDraw(this)) { showNonAdreno = release; return }
|
||||
install(release)
|
||||
}
|
||||
|
||||
@@ -2582,7 +2744,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
showPhantomGate = true
|
||||
return false
|
||||
}
|
||||
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()
|
||||
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.canDraw(this)
|
||||
if (warn && available != null) { showNonAdreno = available; return false }
|
||||
startActivity(intent)
|
||||
return true
|
||||
@@ -2704,6 +2866,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val STATE_HOME_CHOICE_OPEN = "home_choice_open"
|
||||
private const val STATE_GAME_SPACE_OFFERED = "game_space_offered"
|
||||
private const val TAG = "MainActivity"
|
||||
private const val MEDIA_SETTLE_MS = 1500L
|
||||
private const val COMPONENT_RESTORE_MS = 60_000L
|
||||
|
||||
@@ -24,6 +24,9 @@ import kotlin.math.roundToInt
|
||||
|
||||
object HomeApp {
|
||||
private const val ICON_DP = 72
|
||||
private const val GAME_SPACE = "cn.nubia.gamelauncher"
|
||||
private const val GAME_SPACE_ADD = "cn.nubia.gamelauncher.action.GAME_MANAGER"
|
||||
private val GAME_SPACE_GAMES = Uri.parse("content://cn.nubia.gamelauncher.db.AppAddProvider/appadd")
|
||||
|
||||
data class LaunchableApp(
|
||||
val label: String,
|
||||
@@ -54,6 +57,24 @@ object HomeApp {
|
||||
)
|
||||
}
|
||||
|
||||
fun hasGameSpace(context: Context): Boolean =
|
||||
runCatching { context.packageManager.getPackageInfo(GAME_SPACE, 0) }.isSuccess
|
||||
|
||||
fun inGameSpace(context: Context): Boolean =
|
||||
runCatching {
|
||||
context.contentResolver.query(GAME_SPACE_GAMES, arrayOf("component"), null, null, null)?.use { rows ->
|
||||
val prefix = context.packageName + ","
|
||||
generateSequence { if (rows.moveToNext()) rows.getString(0) else null }.any { it.startsWith(prefix) }
|
||||
}
|
||||
}.getOrNull() ?: true
|
||||
|
||||
fun gameSpaceAddIntent(): Intent = Intent(GAME_SPACE_ADD).setPackage(GAME_SPACE)
|
||||
|
||||
fun releaseUnusedHomeEntry(context: Context) {
|
||||
if (isHomeScreenEnabled(context) && !isDefault(context) && hasGameSpace(context))
|
||||
setHomeScreenEnabled(context, false)
|
||||
}
|
||||
|
||||
fun isDefault(context: Context): Boolean {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val roles = context.getSystemService(RoleManager::class.java)
|
||||
@@ -147,8 +168,62 @@ object HomeApp {
|
||||
.getShortcutIconDrawable(info, context.resources.displayMetrics.densityDpi)?.toBitmap(px, px)
|
||||
}.getOrNull()
|
||||
|
||||
fun trackRecents(app: android.app.Application) {
|
||||
app.registerActivityLifecycleCallbacks(object : android.app.Application.ActivityLifecycleCallbacks {
|
||||
override fun onActivityCreated(activity: android.app.Activity, savedInstanceState: android.os.Bundle?) = Unit
|
||||
override fun onActivityStarted(activity: android.app.Activity) = Unit
|
||||
override fun onActivityResumed(activity: android.app.Activity) = syncRecents(activity)
|
||||
override fun onActivityPaused(activity: android.app.Activity) { if (activity is FrontEndActivity) syncRecents(activity) }
|
||||
override fun onActivityStopped(activity: android.app.Activity) = Unit
|
||||
override fun onActivitySaveInstanceState(activity: android.app.Activity, outState: android.os.Bundle) = Unit
|
||||
override fun onActivityDestroyed(activity: android.app.Activity) = Unit
|
||||
})
|
||||
}
|
||||
|
||||
private fun syncRecents(activity: android.app.Activity) =
|
||||
keepOutOfRecents(activity, activity is FrontEndActivity && !SessionState.running && isDefault(activity))
|
||||
|
||||
internal enum class RecentsStep { HIDE, SHOW, FORGET, NONE }
|
||||
|
||||
internal fun recentsStep(hidden: Boolean, owned: Boolean, excluded: Boolean): RecentsStep = when {
|
||||
hidden && !excluded -> RecentsStep.HIDE
|
||||
!hidden && owned && excluded -> RecentsStep.SHOW
|
||||
!hidden && owned -> RecentsStep.FORGET
|
||||
else -> RecentsStep.NONE
|
||||
}
|
||||
|
||||
fun keepOutOfRecents(activity: android.app.Activity, hidden: Boolean) {
|
||||
val prefs = activity.getSharedPreferences("home-recents", Context.MODE_PRIVATE)
|
||||
val owned = prefs.getStringSet("tasks", null).orEmpty()
|
||||
val id = activity.taskId.toString()
|
||||
if (!hidden && id !in owned) return
|
||||
runCatching {
|
||||
@Suppress("DEPRECATION")
|
||||
fun idOf(task: android.app.ActivityManager.AppTask) =
|
||||
if (Build.VERSION.SDK_INT >= 29) task.taskInfo.taskId else task.taskInfo.persistentId
|
||||
val tasks = activity.getSystemService(android.app.ActivityManager::class.java).appTasks
|
||||
val task = tasks.firstOrNull { idOf(it) == activity.taskId } ?: return
|
||||
val excluded = task.taskInfo.baseIntent.flags and Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS != 0
|
||||
val step = recentsStep(hidden, id in owned, excluded)
|
||||
if (step == RecentsStep.NONE) return
|
||||
if (step != RecentsStep.FORGET) task.setExcludeFromRecents(step == RecentsStep.HIDE)
|
||||
val live = tasks.map { idOf(it).toString() }.toSet()
|
||||
val next = owned.filter { it in live && it != id }.toMutableSet()
|
||||
if (step == RecentsStep.HIDE) next += id
|
||||
prefs.edit().putStringSet("tasks", next).apply()
|
||||
}
|
||||
}
|
||||
|
||||
fun startShortcut(context: Context, info: ShortcutInfo) {
|
||||
context.getSystemService(LauncherApps::class.java).startShortcut(info, null, null)
|
||||
val task = generateSequence(context) { (it as? android.content.ContextWrapper)?.baseContext }
|
||||
.filterIsInstance<android.app.Activity>().firstOrNull()?.taskId
|
||||
task?.let { com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(it, true) }
|
||||
try {
|
||||
context.getSystemService(LauncherApps::class.java).startShortcut(info, null, null)
|
||||
} catch (e: Exception) {
|
||||
task?.let { com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(it, false) }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
fun openAppInfo(context: Context, app: LaunchableApp) {
|
||||
|
||||
@@ -12,7 +12,6 @@ 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 ""
|
||||
|
||||
@@ -197,7 +197,6 @@ object HomeWidgets {
|
||||
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
|
||||
|
||||
@@ -20,7 +20,6 @@ internal class ProtonMenu(
|
||||
private val ui: Handler,
|
||||
private val idle: () -> Boolean = { true },
|
||||
) {
|
||||
// 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)
|
||||
|
||||
@@ -71,7 +71,6 @@ class QuestXrActivity : NativeActivity() {
|
||||
}
|
||||
} finally {
|
||||
synchronized(steamVrLock) {
|
||||
// A retiring activity must not stop a replacement's SteamVR session.
|
||||
if (steamVrOwner === this) {
|
||||
if (sessionAlive()) SteamVr.run(this, "stop")
|
||||
steamVrOwner = null
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -18,7 +18,6 @@ object AgentEnv {
|
||||
private const val TAG = "AgentEnv"
|
||||
private const val FILE = "agent-env.json"
|
||||
private const val GUEST_BIN = "/opt/droiddeck-agent/bin"
|
||||
private const val BASE_PATH = "/usr/local/bin:/usr/bin:/bin"
|
||||
private val NAME = Regex("[A-Za-z0-9._-]{1,64}")
|
||||
private val KEY = Regex("[A-Za-z_][A-Za-z0-9_]*")
|
||||
private val lock = Any()
|
||||
@@ -160,7 +159,7 @@ object AgentEnv {
|
||||
}
|
||||
|
||||
private fun pathOf(lines: List<String>) =
|
||||
lines.lastOrNull { it.startsWith("PATH=") }?.substringAfter('=')?.takeIf { it.isNotBlank() } ?: BASE_PATH
|
||||
lines.lastOrNull { it.startsWith("PATH=") }?.substringAfter('=')?.takeIf { it.isNotBlank() } ?: LinuxRuntime.GUEST_PATH
|
||||
|
||||
private fun bin(context: Context): File {
|
||||
val root = LinuxRuntime.rootDir(context).canonicalFile.toPath()
|
||||
|
||||
@@ -118,7 +118,6 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
}
|
||||
}
|
||||
|
||||
// Android keeps the input stream's wake lock while a frozen helper still has it started.
|
||||
public boolean awaitMicReleased(long timeoutMs) {
|
||||
long deadline = System.currentTimeMillis() + timeoutMs;
|
||||
synchronized (micLock) {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.droiddeck.launcher.audio
|
||||
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioTrack
|
||||
import android.util.Log
|
||||
|
||||
object DirectAudioTiming {
|
||||
private const val TAG = "DirectAudioTiming"
|
||||
const val PERIOD_ENV = "AUDIO_DIRECT_PERIOD_MS"
|
||||
const val BUFFER_ENV = "AUDIO_DIRECT_MS"
|
||||
const val SLOW_OUTPUT_PERIOD_MS = 20
|
||||
const val SLOW_OUTPUT_BUFFER_MS = 60
|
||||
|
||||
fun environment(lowLatencyOutput: Boolean): List<String> =
|
||||
if (lowLatencyOutput) emptyList()
|
||||
else listOf("$PERIOD_ENV=$SLOW_OUTPUT_PERIOD_MS", "$BUFFER_ENV=$SLOW_OUTPUT_BUFFER_MS")
|
||||
|
||||
fun lowLatencyOutput(): Boolean = try {
|
||||
val track = AudioTrack.Builder()
|
||||
.setAudioAttributes(AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_GAME)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
|
||||
.build())
|
||||
.setAudioFormat(AudioFormat.Builder()
|
||||
.setEncoding(AudioFormat.ENCODING_PCM_FLOAT)
|
||||
.setSampleRate(48000)
|
||||
.setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
|
||||
.build())
|
||||
.setPerformanceMode(AudioTrack.PERFORMANCE_MODE_LOW_LATENCY)
|
||||
.setTransferMode(AudioTrack.MODE_STREAM)
|
||||
.build()
|
||||
try {
|
||||
track.performanceMode == AudioTrack.PERFORMANCE_MODE_LOW_LATENCY
|
||||
} finally {
|
||||
track.release()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "audio: could not check for low-latency output; DirectAudio keeps its defaults", e)
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -13,15 +13,10 @@ import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
|
||||
/**
|
||||
* A pack built by CI alongside this APK (tools/packs). Main and release builds publish it to
|
||||
* DroidDeck-Components under a content-addressed tag; a PR test build attaches packs that are not there
|
||||
* yet to its pr-N release on DroidDeck-CI. The APK pins the pack's SHA-256, so only the bytes this build
|
||||
* was made with install, whichever host serves them.
|
||||
*/
|
||||
internal class AddonPack(
|
||||
val name: String, private val sha256: String, val size: Long, private val required: List<String>,
|
||||
private val reuseDeviceCopy: Boolean = sha256.isEmpty() && !BuildConfig.CI_BUILD,
|
||||
private val bundle: (Context) -> java.io.InputStream = { it.assets.open("packs/$name.tar.zst") },
|
||||
) {
|
||||
sealed interface State {
|
||||
data object Missing : State
|
||||
@@ -42,13 +37,11 @@ internal class AddonPack(
|
||||
)
|
||||
|
||||
private fun root(context: Context) = File(context.filesDir, "addons/$name")
|
||||
/** App-private and written only after the archive matched the pinned digest. */
|
||||
fun dir(context: Context) = File(root(context), version(context))
|
||||
fun file(context: Context, relative: String) = File(dir(context), relative)
|
||||
|
||||
fun installed(context: Context): Boolean = version(context).isNotEmpty() && File(dir(context), COMPLETE).isFile
|
||||
|
||||
// A build made outside CI pins no packs, so it runs the newest one a CI build already verified and installed.
|
||||
private fun version(context: Context): String = if (!reuseDeviceCopy) sha256 else deviceCopy(context).orEmpty()
|
||||
|
||||
private fun deviceCopy(context: Context): String? = root(context).listFiles().orEmpty()
|
||||
@@ -65,7 +58,6 @@ internal class AddonPack(
|
||||
.also { mutableState.value = it }
|
||||
}
|
||||
|
||||
/** Starts the download in the background unless the pack is already present or on its way. */
|
||||
fun ensure(context: Context, onReady: (Context) -> Unit = {}) {
|
||||
val app = context.applicationContext
|
||||
synchronized(lock) {
|
||||
@@ -80,7 +72,6 @@ internal class AddonPack(
|
||||
}
|
||||
}
|
||||
|
||||
/** Blocks a worker thread until the pack is installed, starting the download if needed. */
|
||||
@JvmOverloads
|
||||
fun await(context: Context, running: () -> Boolean = { true }, onState: (State) -> Unit = {}): Boolean {
|
||||
if (installed(context)) return true
|
||||
@@ -104,7 +95,7 @@ internal class AddonPack(
|
||||
}
|
||||
val root = root(context).apply { mkdirs() }
|
||||
val archive = File(root, "$sha256.tar.zst")
|
||||
val downloaded = urls.any { url ->
|
||||
val downloaded = bundled(context, archive) || urls.any { url ->
|
||||
Downloader.downloadFile(url, archive, true, sha256) { p -> mutableState.value = State.Downloading(p.coerceIn(0f, 1f)) }
|
||||
.also { if (!it) archive.delete() }
|
||||
}
|
||||
@@ -126,6 +117,16 @@ internal class AddonPack(
|
||||
return true
|
||||
}
|
||||
|
||||
internal fun bundled(context: Context, archive: File): Boolean {
|
||||
val copied = runCatching {
|
||||
bundle(context).use { input -> archive.outputStream().use { input.copyTo(it) } }
|
||||
}.isSuccess
|
||||
if (copied && Hashes.sha256(archive).equals(sha256, ignoreCase = true)) return true
|
||||
if (copied) Log.w(TAG, "$name: the bundled pack does not match the pinned digest")
|
||||
archive.delete()
|
||||
return false
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AddonPack"
|
||||
private const val REPO = "Droid-Deck/DroidDeck-Components"
|
||||
|
||||
@@ -42,7 +42,6 @@ object DeviceReport {
|
||||
}
|
||||
}
|
||||
|
||||
/** Name of an ApplicationExitInfo reason code, so a report says "LOW_MEMORY" instead of "3". */
|
||||
internal fun exitReasonName(reason: Int): String = when (reason) {
|
||||
0 -> "UNKNOWN"
|
||||
1 -> "EXIT_SELF"
|
||||
@@ -209,7 +208,7 @@ object DeviceReport {
|
||||
|
||||
h("Drivers")
|
||||
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
|
||||
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
|
||||
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText(SessionPrefs.vkBridge(context))}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
|
||||
if (gpu.model == 740) {
|
||||
val hint = com.droiddeck.launcher.gpu.TpUbwcHint
|
||||
k("TP UBWC hint", hint.forThisDevice(context) ?: "driver default")
|
||||
|
||||
@@ -6,8 +6,20 @@ import com.droiddeck.launcher.R
|
||||
import java.io.File
|
||||
|
||||
object DeviceSupport {
|
||||
fun adreno(): Boolean =
|
||||
private val adrenoGpu by lazy {
|
||||
File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
|
||||
}
|
||||
|
||||
private val maliGpu by lazy { !adrenoGpu && File("/dev/mali0").exists() }
|
||||
|
||||
fun adreno(): Boolean = adrenoGpu
|
||||
|
||||
fun mali(): Boolean = maliGpu
|
||||
|
||||
fun vkBridge(context: Context): Boolean =
|
||||
!adreno() && com.droiddeck.launcher.session.SessionPrefs.vkBridge(context)
|
||||
|
||||
fun canDraw(context: Context): Boolean = adreno() || vkBridge(context)
|
||||
|
||||
fun gpuName(context: Context): String {
|
||||
val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN } else null
|
||||
|
||||
@@ -126,11 +126,9 @@ object DownloadSource {
|
||||
|
||||
fun isGithub(url: String): Boolean = GITHUB_HOSTS.any { url.startsWith("https://$it/") }
|
||||
|
||||
/** Catalogs carry the digests everything else is checked against, so a mirror must never supply one. */
|
||||
fun isCatalog(url: String): Boolean = CATALOGS.any { url.startsWith(it) }
|
||||
|
||||
fun candidates(target: String): List<String> {
|
||||
// GitHub API metadata carries executable URLs and digests; never proxy it.
|
||||
if (isCatalog(target) || target.startsWith("https://api.github.com/")) return listOf(target)
|
||||
val prefs = prefs() ?: return listOf(target)
|
||||
if (!isGithub(target)) return listOf(target)
|
||||
@@ -184,7 +182,6 @@ object DownloadSource {
|
||||
prefs(context)?.edit()?.putString(KEY_PROXY, normalizeProxy(value))?.apply()
|
||||
}
|
||||
|
||||
/** An HTTP proxy every Downloader connection uses, or null when none is configured. */
|
||||
fun httpProxy(): Proxy? = proxyOf(prefs()?.getString(KEY_PROXY, "") ?: "")
|
||||
|
||||
internal fun proxyOf(value: String): Proxy? {
|
||||
|
||||
@@ -91,7 +91,6 @@ public final class Downloader {
|
||||
if (isCancelled(cancelled)) return null;
|
||||
if (i > 0) Log.i(TAG, "retrying " + url + " via " + 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));
|
||||
@@ -103,7 +102,6 @@ public final class Downloader {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Fetches without the mirror list, for a URL whose body is a digest the payload is checked against. */
|
||||
public static String downloadDirect(String url) {
|
||||
return fetch(url).body;
|
||||
}
|
||||
@@ -113,13 +111,11 @@ public final class Downloader {
|
||||
return downloadFile(url, destination, resume, null, progress);
|
||||
}
|
||||
|
||||
/** 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) {
|
||||
@@ -128,13 +124,11 @@ public final class Downloader {
|
||||
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);
|
||||
@@ -149,7 +143,6 @@ public final class Downloader {
|
||||
if (isCancelled(cancelled)) return false;
|
||||
if (i > 0) Log.i(TAG, "retrying " + original + " via " + source);
|
||||
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) {
|
||||
@@ -192,7 +185,6 @@ public final class Downloader {
|
||||
return value != null && !value.isEmpty() && !value.startsWith("W/");
|
||||
}
|
||||
|
||||
/** Only reuse saved bytes when we persisted a strong validator and their source. */
|
||||
private static Identity loadIdentity(File dest, boolean resume, String expectedSha256) {
|
||||
Identity identity = new Identity();
|
||||
File marker = resumeFile(dest);
|
||||
@@ -213,7 +205,6 @@ public final class Downloader {
|
||||
return identity;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Legacy partials or interrupted metadata writes have no trustworthy identity.
|
||||
}
|
||||
if (!discardPartial(dest, identity)) Log.w(TAG, "could not discard unidentified partial " + dest);
|
||||
return identity;
|
||||
@@ -239,7 +230,7 @@ public final class Downloader {
|
||||
try (FileOutputStream out = new FileOutputStream(marker)) {
|
||||
p.store(out, "DroidDeck partial download validator");
|
||||
} catch (IOException e) {
|
||||
marker.delete(); // No valid metadata means no future resume.
|
||||
marker.delete();
|
||||
Log.w(TAG, "cannot persist download validator", e);
|
||||
}
|
||||
}
|
||||
@@ -252,7 +243,6 @@ public final class Downloader {
|
||||
long have = resume && destination.isFile() ? destination.length() : 0;
|
||||
try {
|
||||
if (have > 0 && (!url.equals(identity.source) || !strongETag(identity.etag))) {
|
||||
// A new source or unvalidated bytes must restart from byte zero.
|
||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||
have = 0;
|
||||
}
|
||||
@@ -286,7 +276,6 @@ public final class Downloader {
|
||||
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
|
||||
}
|
||||
if (!appending && have > 0) {
|
||||
// If-Range may legitimately return full 200 when representation changed.
|
||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||
have = 0;
|
||||
}
|
||||
@@ -333,14 +322,12 @@ public final class Downloader {
|
||||
}
|
||||
}
|
||||
|
||||
/** True when a `Content-Range: bytes START-END/TOTAL` header starts exactly at {@code start}. */
|
||||
static boolean rangeStartsAt(String contentRange, long start) {
|
||||
if (contentRange == null) return false;
|
||||
java.util.regex.Matcher m = java.util.regex.Pattern.compile("^\\s*bytes\\s+(\\d+)-\\d+/(?:\\d+|\\*)\\s*$").matcher(contentRange);
|
||||
return m.matches() && Long.parseLong(m.group(1)) == start;
|
||||
}
|
||||
|
||||
/** The complete length in a `Content-Range` header, or -1 when the header leaves it unknown. */
|
||||
static long rangeTotal(String contentRange) {
|
||||
if (contentRange == null) return -1;
|
||||
java.util.regex.Matcher m = java.util.regex.Pattern.compile("^\\s*bytes\\s+\\d+-\\d+/(\\d+)\\s*$").matcher(contentRange);
|
||||
@@ -390,7 +377,6 @@ public final class Downloader {
|
||||
}
|
||||
|
||||
private static HttpURLConnection open(String url, int readTimeoutMs) throws java.io.IOException {
|
||||
// An explicit Proxy routes the connection through the app setting instead of the system-wide proxy.
|
||||
Proxy proxy = DownloadSource.INSTANCE.httpProxy();
|
||||
HttpURLConnection connection = (HttpURLConnection) (proxy != null
|
||||
? new URL(url).openConnection(proxy) : new URL(url).openConnection());
|
||||
|
||||
@@ -34,6 +34,8 @@ object GameEnvironmentOptions {
|
||||
Option("MESA_EXTENSION_MAX_YEAR", "", 0, Type.TEXT),
|
||||
Option("MESA_GL_VERSION_OVERRIDE", "", 0, Type.TEXT),
|
||||
Option("PULSE_LATENCY_MSEC", "", 0, Type.NUMBER),
|
||||
Option("AUDIO_DIRECT_MS", "", 0, Type.NUMBER),
|
||||
Option("AUDIO_DIRECT_PERIOD_MS", "", 0, Type.NUMBER),
|
||||
Option("DROIDDECK_GAME_CORES", "", R.string.game_env_cores, Type.TEXT),
|
||||
Option("DROIDDECK_ANTICHEAT_OFFLINE", "1", R.string.game_env_anticheat_offline, Type.TOGGLE, listOf("0", "1")),
|
||||
Option("WINE_LARGE_ADDRESS_AWARE", "0", 0, Type.TOGGLE, listOf("0", "1")),
|
||||
|
||||
@@ -5,7 +5,6 @@ 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 ->
|
||||
@@ -19,6 +18,5 @@ object GlobalSettings {
|
||||
|
||||
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")
|
||||
}
|
||||
@@ -11,7 +11,6 @@ object LogRedactor {
|
||||
size > 32
|
||||
}
|
||||
|
||||
// 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()
|
||||
}
|
||||
@@ -145,7 +144,6 @@ object LogRedactor {
|
||||
val needs = name.lowercase().takeIf { name.all { it.code < 0x80 } }
|
||||
Learned(Regex("(?i)(?<![A-Za-z0-9_])" + Regex.escape(name) + "(?![A-Za-z0-9_])"), needs)
|
||||
}
|
||||
// A file that could not be read keeps the names learned from it before.
|
||||
accounts = if (unread) (accounts + learned).distinctBy { it.regex.pattern } else learned
|
||||
}
|
||||
|
||||
@@ -228,7 +226,6 @@ object LogRedactor {
|
||||
return out
|
||||
}
|
||||
|
||||
/** The at-rest rewrite reads a file into memory twice; larger logs are only scrubbed on the way out. */
|
||||
const val IN_MEMORY_SCRUB_MAX = 64L * 1024 * 1024
|
||||
|
||||
fun isBinary(file: java.io.File): Boolean = try {
|
||||
@@ -241,8 +238,6 @@ object LogRedactor {
|
||||
true
|
||||
}
|
||||
|
||||
fun isText(file: java.io.File): Boolean = file.isFile && file.length() < IN_MEMORY_SCRUB_MAX && !isBinary(file)
|
||||
|
||||
const val RULES_VERSION = 3
|
||||
|
||||
private val LAN_IPV4 = Regex(
|
||||
|
||||
@@ -52,8 +52,6 @@ object SessionLogCapture {
|
||||
if (t.parentFile?.absolutePath == dir.absolutePath) stop()
|
||||
}
|
||||
|
||||
/** flush() only reaches the page cache, and a hard reset on f2fs lost the last minutes of every
|
||||
* log. Every 2 s the session folder's files (ours and the native parts') are synced to storage. */
|
||||
private fun startSyncing(dir: File): Thread = Thread({
|
||||
while (true) {
|
||||
try { Thread.sleep(2000) } catch (e: InterruptedException) { break }
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
|
||||
class ShortcutsListingReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action == Intent.ACTION_MY_PACKAGE_REPLACED) SteamIntegration.syncShortcutsListing(context)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import android.accessibilityservice.AccessibilityServiceInfo
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.provider.Settings
|
||||
import android.view.accessibility.AccessibilityManager
|
||||
@@ -44,8 +45,6 @@ object SteamIntegration {
|
||||
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 {
|
||||
@@ -55,6 +54,33 @@ object SteamIntegration {
|
||||
return mode == android.app.AppOpsManager.MODE_ERRORED || mode == android.app.AppOpsManager.MODE_IGNORED
|
||||
}
|
||||
|
||||
private fun shortcutsComponent(context: Context) = ComponentName(context, HomeButtonService::class.java)
|
||||
|
||||
fun shortcutsChosen(context: Context): Boolean = shortcutsSelection(context) == true
|
||||
|
||||
private fun shortcutsSelection(context: Context): Boolean? {
|
||||
val target = shortcutsComponent(context)
|
||||
val enabled = runCatching {
|
||||
Settings.Secure.getString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
|
||||
}.getOrElse { return null }.orEmpty()
|
||||
return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == target }
|
||||
}
|
||||
|
||||
fun setShortcutsListed(context: Context, listed: Boolean) {
|
||||
val packages = context.packageManager
|
||||
val component = shortcutsComponent(context)
|
||||
val state = if (listed) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED
|
||||
runCatching {
|
||||
if (packages.getComponentEnabledSetting(component) != state) {
|
||||
packages.setComponentEnabledSetting(component, state, PackageManager.DONT_KILL_APP)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun syncShortcutsListing(context: Context) {
|
||||
shortcutsSelection(context)?.let { setShortcutsListed(context, it) }
|
||||
}
|
||||
|
||||
fun dismissSuggestion(context: Context) {
|
||||
SessionPrefs.sessionPrefs(context).edit().putBoolean("steam_integration_seen", true).apply()
|
||||
}
|
||||
@@ -62,7 +88,6 @@ object SteamIntegration {
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.Settings
|
||||
|
||||
object AllFilesAccess {
|
||||
fun missing(sdk: Int = Build.VERSION.SDK_INT, granted: () -> Boolean = { Environment.isExternalStorageManager() }): Boolean =
|
||||
sdk >= Build.VERSION_CODES.R && !granted()
|
||||
|
||||
fun open(context: Context) {
|
||||
val app = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:" + context.packageName))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(app) }.recoverCatching {
|
||||
context.startActivity(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -311,87 +311,3 @@ fun CollapsibleRail(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun RailTopTabs(
|
||||
items: List<RailItem>,
|
||||
modifier: Modifier = Modifier,
|
||||
links: List<RailLink> = emptyList(),
|
||||
) {
|
||||
Column(modifier = modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
items.forEach { item ->
|
||||
TopTabCell(
|
||||
icon = item.icon,
|
||||
label = item.label,
|
||||
selected = item.selected,
|
||||
onClick = item.onClick,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
if (links.isNotEmpty()) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.padding(horizontal = 2.dp)
|
||||
.width(1.dp)
|
||||
.height(30.dp)
|
||||
.background(MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)),
|
||||
)
|
||||
links.forEach { link ->
|
||||
TopTabCell(link.icon, link.label, selected = false, onClick = link.onClick, isTab = false, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TopTabCell(
|
||||
icon: ImageVector,
|
||||
label: String,
|
||||
selected: Boolean,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
isTab: Boolean = true,
|
||||
) {
|
||||
val tint = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = modifier
|
||||
.clip(RoundedCornerShape(9.dp))
|
||||
.background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.focusGlide(RoundedCornerShape(9.dp))
|
||||
.then(
|
||||
if (isTab) {
|
||||
Modifier.selectable(selected = selected, role = androidx.compose.ui.semantics.Role.Tab, onClick = onClick)
|
||||
} else {
|
||||
Modifier.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onClick)
|
||||
},
|
||||
)
|
||||
.padding(vertical = 6.dp, horizontal = 1.dp),
|
||||
) {
|
||||
Icon(icon, contentDescription = label, tint = tint, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
label,
|
||||
color = tint,
|
||||
fontSize = 8.5.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
letterSpacing = 0.2.sp,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.height(2.dp)
|
||||
.width(if (selected) 16.dp else 0.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(if (selected) MaterialTheme.colorScheme.primary else Color.Transparent),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -498,6 +498,25 @@ fun FileManagerScreen(
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
val drives = remember(storageTick) { StorageRoots.list(context) }
|
||||
var accessDrive by remember { mutableStateOf<String?>(null) }
|
||||
fun unreadable(drive: StorageRoot) {
|
||||
if (AllFilesAccess.missing()) accessDrive = drive.label
|
||||
else Toast.makeText(context, context.getString(R.string.fm_drive_not_readable, drive.label), Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
accessDrive?.let { label ->
|
||||
OutlinedAlertDialog(
|
||||
onDismissRequest = { accessDrive = null },
|
||||
title = { Text(stringResource(R.string.fm_drive_access_title, label)) },
|
||||
text = { Text(stringResource(R.string.fm_drive_access_text)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
accessDrive = null
|
||||
AllFilesAccess.open(context)
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.upd_open_settings)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { accessDrive = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
val linuxRoot = remember(storageTick) {
|
||||
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context).takeIf { File(it, "usr").isDirectory }
|
||||
}
|
||||
@@ -747,11 +766,7 @@ fun FileManagerScreen(
|
||||
if (drive.readable) {
|
||||
openDrive(drive.dir)
|
||||
} else {
|
||||
Toast.makeText(
|
||||
context,
|
||||
context.getString(R.string.fm_drive_not_readable, drive.label),
|
||||
Toast.LENGTH_SHORT,
|
||||
).show()
|
||||
unreadable(drive)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
@@ -1072,7 +1087,7 @@ fun FileManagerScreen(
|
||||
add(locItem(stringResource(R.string.fm_drive_internal), Icons.Filled.Smartphone, File("/storage/emulated/0")))
|
||||
drives.filter { it.removable }.forEach { d ->
|
||||
add(RailItem(d.label, Icons.Filled.SdStorage, !showFavorites && currentRoot.absolutePath == d.dir.absolutePath) {
|
||||
showFavorites = false; if (d.readable) openDrive(d.dir)
|
||||
showFavorites = false; if (d.readable) openDrive(d.dir) else unreadable(d)
|
||||
})
|
||||
}
|
||||
linuxRoot?.let { add(locItem(stringResource(R.string.fm_drive_linux), Icons.Filled.Terminal, it)) }
|
||||
|
||||
@@ -57,7 +57,6 @@ object FileOps {
|
||||
return true
|
||||
}
|
||||
if (!copyWithProgress(src, dst, progress, isCancelled)) return false
|
||||
// Once the destination is committed, finish deleting the source.
|
||||
return delete(src)
|
||||
}
|
||||
|
||||
|
||||
@@ -63,7 +63,6 @@ object StorageRoots {
|
||||
}
|
||||
return true
|
||||
}
|
||||
// vold-managed locations only hold removable volumes, whatever the fstype is.
|
||||
return path.startsWith("/storage/") || path.startsWith("/mnt/media_rw/")
|
||||
}
|
||||
|
||||
@@ -92,8 +91,6 @@ object StorageRoots {
|
||||
.forEachIndexed { index, volume ->
|
||||
val uuid = volume.uuid?.takeIf { it.isNotBlank() }
|
||||
val dirName = volume.directory?.name?.takeIf { it.isNotBlank() }
|
||||
// Unmounted volumes often report neither uuid nor directory; never drop the
|
||||
// volume or a plugged-in drive stays invisible with no explanation.
|
||||
val descSlug = volume.getDescription(context)?.trim()
|
||||
?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
|
||||
?.replace(Regex("[^A-Za-z0-9._-]+"), "-")
|
||||
@@ -108,8 +105,6 @@ object StorageRoots {
|
||||
if (name != null) {
|
||||
entry.candidates += File("/storage/$name")
|
||||
entry.candidates += File("/mnt/media_rw/$name")
|
||||
// Only strict uuid matches own an app directory; a loose match would
|
||||
// attach another volume's folder to this entry.
|
||||
if (uuid != null) appDirs.filter { belongsTo(storageManager!!, it, volume) }
|
||||
.forEach { entry.seeds += it }
|
||||
}
|
||||
@@ -122,8 +117,6 @@ object StorageRoots {
|
||||
File("/mnt/media_rw").listFiles().orEmpty().forEach { child ->
|
||||
if (child.isDirectory) volumeOf(child.name).candidates += child
|
||||
}
|
||||
// USB OTG drives do not always appear as storage volumes or under /storage for
|
||||
// third-party apps, but their kernel mounts are still visible in /proc/mounts.
|
||||
for (mount in externalMounts()) {
|
||||
val entry = volumeOf(mount.name)
|
||||
if (entry.label == null) entry.label = mount.name
|
||||
|
||||
@@ -243,6 +243,8 @@ object AddedGameArt {
|
||||
val steam: (String, File, Set<Slot>) -> Boolean,
|
||||
val sgdbGame: (String, Int?, String) -> Int?,
|
||||
val sgdb: (String, Int, File, Set<Slot>) -> Boolean,
|
||||
val sgdbExactGame: (String, Int?, String) -> Int? = { _, _, _ -> null },
|
||||
val battleNetArt: (Context, BattleNet.Title) -> Boolean = { _, _ -> false },
|
||||
)
|
||||
|
||||
private val network = Sources(
|
||||
@@ -251,6 +253,8 @@ object AddedGameArt {
|
||||
steam = ::download,
|
||||
sgdbGame = SteamGridDb::gameId,
|
||||
sgdb = SteamGridDb::download,
|
||||
sgdbExactGame = SteamGridDb::exactGameId,
|
||||
battleNetArt = { context, title -> BattleNet.fetchCovers(context, listOf(BattleNet.artTitle(title))) },
|
||||
)
|
||||
|
||||
private val EXTRAS = setOf(Slot.LOGO, Slot.ICON)
|
||||
@@ -287,14 +291,20 @@ object AddedGameArt {
|
||||
var sgdbDown = false
|
||||
var changed = false
|
||||
for (game in games) {
|
||||
if (forgetOtherAppsArt(context, game)) changed = true
|
||||
if (forgetNameMatchedBattleNetArt(context, game)) changed = true
|
||||
val battleNetTitle = game.storeId?.takeIf { game.source == Store.BATTLENET.id }?.let(BattleNet::title)
|
||||
if (battleNetTitle != null && runCatching { sources.battleNetArt(context, battleNetTitle) }.getOrDefault(false)) changed = true
|
||||
val cache = cacheDir(context, game)
|
||||
val start = missing(context, game)
|
||||
val again = refetch(cache) intersect start
|
||||
if (again.isEmpty()) File(cache, REFETCH).delete()
|
||||
val full = Slot.COVER in start
|
||||
val allowed = if (full) Slot.values().toSet() else EXTRAS
|
||||
val allowed = if (full) Slot.values().toSet() else EXTRAS + again
|
||||
var need = start intersect allowed
|
||||
if (need.isEmpty() || (need == setOf(Slot.ICON) && sgdbKey.isEmpty())) continue
|
||||
val cache = cacheDir(context, game)
|
||||
val tried = File(cache, EXTRAS_TRIED)
|
||||
if (!full && tried.isFile && tried.lastModified() >= keyChangedAt && System.currentTimeMillis() - tried.lastModified() < RETRY_AFTER_MS) continue
|
||||
if (!full && again.isEmpty() && tried.isFile && tried.lastModified() >= keyChangedAt && System.currentTimeMillis() - tried.lastModified() < RETRY_AFTER_MS) continue
|
||||
cache.mkdirs()
|
||||
if (Slot.LOGO in need && game.source != Library.ADDED && runCatching { sources.storeLogo(game) }.getOrDefault(false)) {
|
||||
changed = true
|
||||
@@ -315,7 +325,7 @@ object AddedGameArt {
|
||||
if (need.isNotEmpty() && sgdbKey.isNotEmpty()) {
|
||||
if (sgdbDown) asked = false else try {
|
||||
val gridId = remembered(File(cache, "sgdb-id"), keyChangedAt) {
|
||||
sources.sgdbGame(sgdbKey, match.appId, game.name)?.toString()
|
||||
(if (battleNetTitle != null) sources.sgdbExactGame else sources.sgdbGame)(sgdbKey, match.appId, game.name)?.toString()
|
||||
}?.toIntOrNull()
|
||||
if (gridId != null && sources.sgdb(sgdbKey, gridId, cache, need)) changed = true
|
||||
} catch (e: Exception) {
|
||||
@@ -324,11 +334,57 @@ object AddedGameArt {
|
||||
asked = false
|
||||
}
|
||||
}
|
||||
if ((missing(context, game) intersect EXTRAS).isEmpty()) tried.delete() else if (asked) tried.writeText("")
|
||||
val left = missing(context, game)
|
||||
if (again.isNotEmpty()) keepRefetch(cache, again intersect left)
|
||||
if ((left intersect EXTRAS).isEmpty()) tried.delete() else if (asked) tried.writeText("")
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
internal const val REFETCH = "refetch"
|
||||
|
||||
private fun refetch(cache: File): Set<Slot> =
|
||||
runCatching { File(cache, REFETCH).readText() }.getOrDefault("").split(',').mapNotNull { key -> Slot.values().firstOrNull { it.key == key } }.toSet()
|
||||
|
||||
private fun keepRefetch(cache: File, slots: Set<Slot>) {
|
||||
if (slots.isEmpty()) File(cache, REFETCH).delete() else File(cache, REFETCH).writeText(slots.joinToString(",") { it.key })
|
||||
}
|
||||
|
||||
internal const val BATTLENET_ART_CHECKED = "battlenet-art-2"
|
||||
|
||||
internal fun forgetNameMatchedBattleNetArt(context: Context, game: AddedGames.Game): Boolean {
|
||||
val title = game.storeId?.takeIf { game.source == Store.BATTLENET.id }?.let(BattleNet::title) ?: return false
|
||||
val cache = cacheDir(context, game)
|
||||
val checked = File(cache, BATTLENET_ART_CHECKED)
|
||||
if (title.steam != null || checked.isFile) return false
|
||||
val dropped = EXTRAS.filter { File(cache, SteamGridDb.cacheName(it)).delete() }
|
||||
EXTRAS.forEach { File(cache, SteamGridDb.cacheName(it) + ".src").delete() }
|
||||
listOf("sgdb-id", EXTRAS_TRIED).forEach { File(cache, it).delete() }
|
||||
cache.mkdirs()
|
||||
checked.writeText("")
|
||||
return dropped.isNotEmpty()
|
||||
}
|
||||
|
||||
internal fun forgetOtherAppsArt(context: Context, game: AddedGames.Game): Boolean {
|
||||
val cache = cacheDir(context, game)
|
||||
val recorded = SteamMatch.get(context, game.folder.path)?.takeIf { it.appId != null }
|
||||
val legacy = runCatching { File(cache, "steam-appid").readText().trim().toInt() }.getOrNull()?.takeIf { it > 0 }
|
||||
val before = recorded?.appId ?: legacy ?: return false
|
||||
val identity = runCatching { GameIdentifier.identify(game.exe) }.getOrNull()
|
||||
val now = identity?.appId
|
||||
val fromFiles = recorded?.certainty == SteamMatch.Certainty.FILES || before == GameIdentifier.SPACEWAR
|
||||
if (now == before || (now == null && !fromFiles)) return false
|
||||
SteamMatch.put(context, game.folder.path,
|
||||
if (identity != null && now != null) SteamMatch.Match(now, SteamMatch.Certainty.FILES, identity.source.name.lowercase(), System.currentTimeMillis())
|
||||
else SteamMatch.Match(null, SteamMatch.Certainty.NONE, "", 0))
|
||||
val dropped = Slot.values().filter { File(cache, SteamGridDb.cacheName(it)).delete() }.toSet()
|
||||
Slot.values().forEach { File(cache, SteamGridDb.cacheName(it) + ".src").delete() }
|
||||
listOf("sgdb-id", "steam-appid", EXTRAS_TRIED).forEach { File(cache, it).delete() }
|
||||
keepRefetch(cache, refetch(cache) + dropped)
|
||||
Log.i(TAG, "${game.name}: its files no longer name Steam app $before; its art is fetched again")
|
||||
return dropped.isNotEmpty()
|
||||
}
|
||||
|
||||
internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match {
|
||||
if (game.source == Store.BATTLENET.id) {
|
||||
val id = game.storeId?.let(BattleNet::title)?.steam
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONObject
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SteamLibraries
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
@@ -69,6 +70,10 @@ object AddedGames {
|
||||
if (path.startsWith("$roms/")) return "/root/ROMs/" + path.removePrefix("$roms/")
|
||||
}
|
||||
StoreInstallRoot.externalGuestPath(context, host)?.let { return it }
|
||||
for (lib in SteamLibraries.list(context)) {
|
||||
if (path == lib.path) return lib.guest
|
||||
if (path.startsWith("${lib.path}/")) return lib.guest + "/" + path.removePrefix("${lib.path}/")
|
||||
}
|
||||
GameStorage.effective(context)?.let { lib ->
|
||||
if (path.startsWith("${lib.path}/")) return "$LIBRARY/" + path.removePrefix("${lib.path}/")
|
||||
}
|
||||
@@ -83,6 +88,7 @@ object AddedGames {
|
||||
if (!guest.startsWith("/") || guest.split('/').any { it == ".." }) return null
|
||||
val mapped = roots(context).map { it.host to it.guest } + StoreInstallRoot.externalRoots(context) +
|
||||
listOfNotNull(GameStorage.effective(context)?.let { File(it.path) to LIBRARY }) +
|
||||
SteamLibraries.list(context).map { it.host to it.guest } +
|
||||
(android.os.Environment.getExternalStorageDirectory() to "/root/Storage")
|
||||
for ((host, root) in mapped.sortedByDescending { it.second.length }) {
|
||||
if (guest == root) return host
|
||||
@@ -170,9 +176,9 @@ object AddedGames {
|
||||
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() } }
|
||||
val dirs = files.filter { it.isDirectory && !it.name.startsWith(".") && !isSteamLibraryFolder(it.name) }.sortedBy { it.name.lowercase() }
|
||||
if (dirs.any { it.name.lowercase() in GAME_PARTS || GameExePicker.auxiliaryDir(it) }) return null
|
||||
return dirs.filter { rank(it).exes.isNotEmpty() }.takeIf { it.size >= 2 }
|
||||
}
|
||||
|
||||
private fun expand(folder: File, entries: Set<String>): List<File> =
|
||||
@@ -180,7 +186,9 @@ object AddedGames {
|
||||
|
||||
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. */
|
||||
private fun libraryDepotInstalls(context: Context): List<File> =
|
||||
SteamLibraries.list(context).flatMap { SteamLibraries.depotInstalls(File(it.path, "steamapps/common")) }
|
||||
|
||||
internal fun isSteamLibraryFolder(name: String): Boolean =
|
||||
name.equals("steamapps", ignoreCase = true) || name == com.droiddeck.launcher.session.GameStorage.X64_CARD_DIR
|
||||
|
||||
@@ -208,6 +216,7 @@ object AddedGames {
|
||||
if (folder.path in removed || !folder.isDirectory) continue
|
||||
scanGame(context, folder, out, single = entry)
|
||||
}
|
||||
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out)
|
||||
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out)
|
||||
for (game in com.droiddeck.launcher.runtime.BattleNet.games(context)) {
|
||||
if (game.folder.path !in removed) com.droiddeck.launcher.runtime.BattleNet.shortcut(context, game)?.let(out::add)
|
||||
@@ -254,6 +263,7 @@ object AddedGames {
|
||||
entries.map { File(it.folder) }.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 }
|
||||
libraryDepotInstalls(context).firstOrNull(::holds)?.let { return it }
|
||||
val removed = SessionPrefs.removedAddedGames(context)
|
||||
val dirs = listOfNotNull(
|
||||
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
|
||||
@@ -315,7 +325,6 @@ object AddedGames {
|
||||
|
||||
fun addFolder(context: Context, dir: File, onGame: (Game) -> Unit = {}, onChecking: (String?) -> Unit = {}, showHidden: Boolean = false): FolderResult {
|
||||
val app = context.applicationContext
|
||||
// Binds are mounted at session start, so a new one reaches the session from the next start.
|
||||
if (guestPath(app, dir) == null) bindFolder(app, dir)
|
||||
val removed = SessionPrefs.removedAddedGames(app).toSet()
|
||||
val listed = listedFolders(app, removed)
|
||||
@@ -372,6 +381,7 @@ object AddedGames {
|
||||
}
|
||||
AddedExes.list(context).filter { it.folder !in removed }.forEach { out.add(canonical(File(it.folder))) }
|
||||
StoreInstallRoot.gameFolders(context).forEach { out.add(canonical(it)) }
|
||||
libraryDepotInstalls(context).filter { it.path !in removed }.forEach { out.add(canonical(it)) }
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -416,7 +426,14 @@ object AddedGames {
|
||||
?.takeIf { SessionPrefs.adoptAddedGameExe(context, folder.path, picked, it.path, rev) }
|
||||
val exe = adopted ?: found
|
||||
val guestExe = if (adopted != null) guestPath(context, adopted) ?: return else foundGuest
|
||||
val storeExe = sidecar?.exeFile(folder)
|
||||
val launched = adopted ?: chosen ?: storeExe?.takeIf { it.isFile }
|
||||
val storeOwnExe = launched != null && storeExe != null && canonical(launched) == canonical(storeExe)
|
||||
val sidecarDir = sidecar?.workdir?.takeIf { storeOwnExe }?.let { dir ->
|
||||
guestPath(context, if (dir.isEmpty()) folder else File(folder, dir))
|
||||
}
|
||||
val guestDir = SessionPrefs.addedGameStartIn(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() }
|
||||
?: sidecarDir
|
||||
?: guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return
|
||||
val steamId = config?.let { steamRoute(it, appId) }
|
||||
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
|
||||
|
||||
@@ -111,10 +111,7 @@ object AutoComponents {
|
||||
|
||||
@VisibleForTesting internal var gameRunning: () -> Boolean = { gameProcessRunning() }
|
||||
|
||||
private fun gameProcessRunning(): Boolean = File("/proc").listFiles()?.any { p ->
|
||||
p.name.all(Char::isDigit) && runCatching { String(File(p, "cmdline").readBytes()).replace('\u0000', ' ') }.getOrNull()
|
||||
?.let { it.contains("SteamLaunch AppId=") || it.contains("proton waitforexitandrun") } == true
|
||||
} == true
|
||||
private fun gameProcessRunning(): Boolean = com.droiddeck.launcher.session.SteamGameProcess.running()
|
||||
|
||||
fun queueInSession(context: Context, game: Library.SteamGame) {
|
||||
if (appKey(game) == null) return
|
||||
|
||||
@@ -54,21 +54,6 @@ object DependencyDetector {
|
||||
"d3dx9", "d3dx11", "xact", "xact_x64", "xna31", "xna40", "physx", "oalinst", "XLiveRedist",
|
||||
)
|
||||
|
||||
fun detectForExe(exeFile: File): List<Recommendation> {
|
||||
val start = exeFile.absoluteFile.parentFile ?: return emptyList()
|
||||
var d: File? = start
|
||||
var depth = 0
|
||||
while (d != null && depth < 4) {
|
||||
val hasRedistContainer = try {
|
||||
d.listFiles()?.any { it.isDirectory && REDIST_DIR_RE.matches(it.name.lowercase(Locale.US)) } == true
|
||||
} catch (_: Throwable) { false }
|
||||
if (hasRedistContainer) return detect(d)
|
||||
d = d.parentFile
|
||||
depth++
|
||||
}
|
||||
return detect(start)
|
||||
}
|
||||
|
||||
fun detect(gameDir: File): List<Recommendation> {
|
||||
if (!gameDir.isDirectory) return emptyList()
|
||||
val hits = LinkedHashMap<String, Recommendation>()
|
||||
|
||||
@@ -89,6 +89,8 @@ object GameExePicker {
|
||||
return score
|
||||
}
|
||||
|
||||
internal fun auxiliaryDir(dir: File): Boolean = skipDir(dir, dir.name)
|
||||
|
||||
private fun skipDir(dir: File, relative: String): Boolean {
|
||||
val name = dir.name.lowercase().trim()
|
||||
if (name in SKIP_DIRS || SKIP_DIR_PREFIX.any { name.startsWith(it) }) return true
|
||||
|
||||
@@ -5,6 +5,7 @@ import java.io.File
|
||||
object GameIdentifier {
|
||||
|
||||
private const val MAX_PARENT_DEPTH = 6
|
||||
internal const val SPACEWAR = 480
|
||||
|
||||
enum class Source { STEAM_APPID_TXT, STEAM_MANIFEST_ACF, STEAM_EMU_INI, GOG_INFO, PE_VERSION, FILENAME, NONE }
|
||||
enum class Confidence { HIGH, MEDIUM, LOW }
|
||||
@@ -92,7 +93,7 @@ object GameIdentifier {
|
||||
for (candidate in arrayOf(File(dir, "steam_appid.txt"), File(dir, "steam_settings/steam_appid.txt"))) {
|
||||
val id = readSmallTextFile(candidate)?.removePrefix("\uFEFF")?.trim()
|
||||
?.takeWhile { it.isDigit() }?.toIntOrNull()
|
||||
if (id != null && id > 0) return id
|
||||
if (id != null && id > 0 && id != SPACEWAR) return id
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -111,7 +112,7 @@ object GameIdentifier {
|
||||
for (f in candidates) {
|
||||
val text = readSmallTextFile(f) ?: continue
|
||||
val id = re.find(text)?.groupValues?.getOrNull(1)?.toIntOrNull()
|
||||
if (id != null && id > 0) return id
|
||||
if (id != null && id > 0 && id != SPACEWAR) return id
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -133,7 +134,8 @@ object GameIdentifier {
|
||||
val match = manifests.firstOrNull { m ->
|
||||
val text = readSmallTextFile(m) ?: return@firstOrNull false
|
||||
val installdir = vdfValue(text, "installdir")
|
||||
gameFolder != null && installdir != null && installdir.equals(gameFolder, ignoreCase = true)
|
||||
gameFolder != null && installdir != null && installdir.equals(gameFolder, ignoreCase = true) &&
|
||||
vdfValue(text, "appid")?.toIntOrNull() != SPACEWAR
|
||||
} ?: return null
|
||||
|
||||
val text = readSmallTextFile(match) ?: return null
|
||||
|
||||
@@ -24,15 +24,33 @@ object GamesFolderMigration {
|
||||
for (root in roots) {
|
||||
var n = 0
|
||||
val steamInstalls = AddedGames.steamInstallDirs(root.host)
|
||||
for (folder in root.host.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() }.orEmpty()) {
|
||||
if (AddedGames.isSteamLibraryFolder(folder.name) || folder.name.lowercase() in steamInstalls) continue
|
||||
if (folder.absolutePath in storeRoots || StoreGameSidecar.read(folder) != null) continue
|
||||
if (folder.path in entries) continue
|
||||
val picked = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
|
||||
val exe = picked ?: AddedGames.rank(folder).exes.firstOrNull() ?: continue
|
||||
AddedExes.put(context, AddedExes.Entry(folder.path, exe.path, picked = picked != null))
|
||||
entries.add(folder.path)
|
||||
if (folder.path !in removed) n++
|
||||
for (top in root.host.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() }.orEmpty()) {
|
||||
if (AddedGames.isSteamLibraryFolder(top.name) || top.name.lowercase() in steamInstalls) continue
|
||||
if (top.absolutePath in storeRoots || StoreGameSidecar.read(top) != null) continue
|
||||
if (top.path in entries) continue
|
||||
val topPick = SessionPrefs.addedGameExe(context, top.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
|
||||
val groups = AddedGames.groupGames(top)
|
||||
val played = topPick ?: groups?.let { AddedGames.rank(top).exes.firstOrNull() }
|
||||
val owner = played?.let { exe -> top.listFiles { f -> f.isDirectory }?.firstOrNull { exe.path.startsWith(it.path + File.separator) } }
|
||||
val folders = when {
|
||||
groups == null -> listOf(top)
|
||||
topPick == null || owner in groups -> groups
|
||||
owner == null || owner.name.startsWith(".") || AddedGames.isSteamLibraryFolder(owner.name) -> listOf(top)
|
||||
else -> (groups + owner).sortedBy { it.name.lowercase() }
|
||||
}
|
||||
for (folder in folders) {
|
||||
if (folder.absolutePath in storeRoots || StoreGameSidecar.read(folder) != null) continue
|
||||
if (folder.path in entries) continue
|
||||
val picked = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
|
||||
?: topPick?.takeIf { it.path.startsWith(folder.path + File.separator) }
|
||||
val ranked = AddedGames.rank(folder).exes.firstOrNull()
|
||||
val exe = picked ?: played?.takeIf { folder == owner } ?: ranked ?: continue
|
||||
AddedExes.put(context, AddedExes.Entry(folder.path, exe.path, picked = picked != null || exe != ranked))
|
||||
entries.add(folder.path)
|
||||
if (folder != top && folder == owner) SessionPrefs.inheritAddedGame(context, top.path, folder.path)
|
||||
if (folder != top && top.path in removed) SessionPrefs.setAddedGameRemoved(context, folder.path, true)
|
||||
else if (folder.path !in removed) n++
|
||||
}
|
||||
}
|
||||
Log.i(TAG, "games: migrated ${root.host} → $n games")
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SteamLibraries
|
||||
import com.droiddeck.launcher.session.SecondaryLibrary
|
||||
import java.io.File
|
||||
|
||||
@@ -87,13 +88,14 @@ object Library {
|
||||
|
||||
internal fun steamLibraries(context: Context, arch: String = SessionPrefs.activeSteamClientArch(context)): List<Pair<File, String>> {
|
||||
val root = SessionPrefs.steamRoot(context, arch)
|
||||
// The session gives the x86-64 client only its card folder; the games folders stay the arm64 client's.
|
||||
val card = GameStorage.effective(context)
|
||||
if (arch == "x86_64") return listOfNotNull(root to "internal", card?.let { File(it.path, GameStorage.X64_CARD_DIR) to it.label })
|
||||
val added = SteamLibraries.list(context).filter { it.host.isDirectory }
|
||||
if (arch == "x86_64") return listOfNotNull(root to "internal", card?.let { File(it.path, GameStorage.X64_CARD_DIR) to it.label }) +
|
||||
added.map { it.x64Host to it.label }
|
||||
return listOfNotNull(
|
||||
root to "internal",
|
||||
card?.let { File(it.path) to it.label },
|
||||
) + GameStorage.gamesFolderLibraries(context).map { it.host to it.label }
|
||||
) + added.map { it.host to it.label } + GameStorage.gamesFolderLibraries(context).map { it.host to it.label }
|
||||
}
|
||||
|
||||
fun protonPrefix(
|
||||
@@ -101,15 +103,21 @@ object Library {
|
||||
libraries: List<File> = steamLibraries(context).map { it.first },
|
||||
): File? {
|
||||
val ids = listOf(appId.toString(), java.lang.Integer.toString(appId.toInt())).distinct()
|
||||
return prefixRoots(context, libraries, preferredLibrary).asSequence()
|
||||
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
|
||||
.firstOrNull { it.isDirectory }
|
||||
}
|
||||
|
||||
fun compatdataDirs(context: Context, libraries: List<File> = steamLibraries(context).map { it.first }): List<File> =
|
||||
prefixRoots(context, libraries).map { File(it, "steamapps/compatdata") }.filter { it.isDirectory }
|
||||
|
||||
private fun prefixRoots(context: Context, libraries: List<File>, preferredLibrary: File? = null): List<File> {
|
||||
val secondary = libraries.drop(1).mapNotNull { runCatching { it.canonicalPath }.getOrNull() }.toSet()
|
||||
fun prefixRoot(root: File): File = if (runCatching { root.canonicalPath }.getOrNull() in secondary)
|
||||
SecondaryLibrary.privateRoot(context.filesDir, root).takeIf { File(it, "steamapps/compatdata").isDirectory } ?: root
|
||||
else root
|
||||
val roots = (listOfNotNull(preferredLibrary) + libraries).map(::prefixRoot)
|
||||
return (listOfNotNull(preferredLibrary) + libraries).map(::prefixRoot)
|
||||
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
|
||||
return roots.asSequence()
|
||||
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
|
||||
.firstOrNull { it.isDirectory }
|
||||
}
|
||||
|
||||
fun steamGames(
|
||||
@@ -172,7 +180,6 @@ object Library {
|
||||
}
|
||||
}
|
||||
|
||||
/** Apps the user hid (the "hidden" collection) or marked private in Steam. */
|
||||
internal fun concealedSteamApps(root: File): Set<Long> {
|
||||
val config = AddedGames.accountConfig(root) ?: return emptySet()
|
||||
val hidden = runCatching {
|
||||
@@ -213,7 +220,6 @@ object Library {
|
||||
return (steam + own.map { g -> addedGame(context, g, roots, played[g.appId] ?: 0L) }).distinctBy { it.gameId }
|
||||
}
|
||||
|
||||
/** Steam's LastPlayTime for each non-Steam shortcut, by its unsigned shortcut app id. */
|
||||
internal fun shortcutsLastPlayed(root: File): Map<Long, Long> = runCatching {
|
||||
val config = AddedGames.accountConfig(root) ?: return emptyMap()
|
||||
val bytes = File(config, "shortcuts.vdf").takeIf { it.isFile }?.readBytes() ?: return emptyMap()
|
||||
|
||||
@@ -10,7 +10,6 @@ object LibraryCache {
|
||||
private const val TAG = "LibraryCache"
|
||||
private fun file(context: Context) = File(context.filesDir, "library-cache.json")
|
||||
|
||||
/** The cached games and whether they are the x86-64 client's; a cache written as a bare list is arm64's. */
|
||||
@Synchronized
|
||||
fun snapshot(context: Context): Pair<List<Library.SteamGame>, Boolean> = runCatching {
|
||||
val f = file(context)
|
||||
@@ -36,7 +35,6 @@ object LibraryCache {
|
||||
|
||||
fun listedX64(context: Context): Boolean = snapshot(context).second
|
||||
|
||||
/** Without [x64] the list keeps the client already recorded. */
|
||||
@Synchronized
|
||||
fun save(context: Context, games: List<Library.SteamGame>, x64: Boolean? = null) {
|
||||
runCatching {
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.frontend
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Where Steam pins a game's logo on its hero image and how big it draws it; the same JSON Steam keeps in `<appid>.json`. */
|
||||
object LogoPosition {
|
||||
enum class Pin(val steam: String) {
|
||||
UPPER_LEFT("UpperLeft"), UPPER_CENTER("UpperCenter"), CENTER("CenterCenter"), BOTTOM_LEFT("BottomLeft"), BOTTOM_CENTER("BottomCenter");
|
||||
@@ -17,7 +16,6 @@ object LogoPosition {
|
||||
const val MIN_PCT = 10
|
||||
const val MAX_PCT = 100
|
||||
|
||||
/** What Steam draws when a game has no custom position. */
|
||||
val DEFAULT = Value(Pin.BOTTOM_LEFT, 50, 50)
|
||||
|
||||
private const val VERSION = 1
|
||||
@@ -25,7 +23,6 @@ object LogoPosition {
|
||||
|
||||
fun sized(pin: Pin, size: Int): Value = size.coerceIn(MIN_PCT, MAX_PCT).let { Value(pin, it, it) }
|
||||
|
||||
/** `{"nVersion":1,"logoPosition":{...}}`, with whatever else [into] already held kept as it was. */
|
||||
fun toJson(value: Value, into: JSONObject = JSONObject()): JSONObject = into
|
||||
.put("nVersion", VERSION)
|
||||
.put(KEY, JSONObject().put("pinnedPosition", value.pin.steam).put("nWidthPct", value.widthPct).put("nHeightPct", value.heightPct))
|
||||
@@ -39,7 +36,6 @@ object LogoPosition {
|
||||
return Value(pin, inner.optInt("nWidthPct").coerceIn(MIN_PCT, MAX_PCT), inner.optInt("nHeightPct").coerceIn(MIN_PCT, MAX_PCT))
|
||||
}
|
||||
|
||||
/** [existing] without the logo position; null when nothing but the version number would be left. */
|
||||
fun without(existing: JSONObject): JSONObject? {
|
||||
existing.remove(KEY)
|
||||
val rest = existing.keys().asSequence().filter { it != "nVersion" }.toList()
|
||||
|
||||
@@ -7,11 +7,9 @@ import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
|
||||
/** Steam keeps a game's custom art in `userdata/<account>/config/grid`; this is where DroidDeck's choices and Steam's meet. */
|
||||
object SteamGrid {
|
||||
private const val TAG = "SteamGrid"
|
||||
|
||||
/** Every change to a game's art, here or in a scan, takes this first so two of them never interleave. */
|
||||
internal val lock = Any()
|
||||
private const val MANIFEST = ".droiddeck-art.json"
|
||||
private val SUFFIX = mapOf(AddedGameArt.Slot.COVER to "p", AddedGameArt.Slot.WIDE to "", AddedGameArt.Slot.BACKGROUND to "_hero", AddedGameArt.Slot.LOGO to "_logo")
|
||||
@@ -36,7 +34,6 @@ object SteamGrid {
|
||||
|
||||
private fun signature(file: File?) = if (file == null) "" else "${file.length()}:${file.lastModified()}"
|
||||
|
||||
/** Each Steam client has its own grid folder, so what was last seen there is kept per client. */
|
||||
private fun sigName(context: Context, key: String) =
|
||||
if (SessionPrefs.activeSteamClientArch(context) == "x86_64") "grid-x86_64-$key" else "grid-$key"
|
||||
|
||||
@@ -45,10 +42,6 @@ object SteamGrid {
|
||||
private const val GRID_ID = ".droiddeck-grid"
|
||||
private const val UNKNOWN_GRID = "?"
|
||||
|
||||
/**
|
||||
* A random id kept in the grid folder, so a record made against another account's folder, or one wiped with the
|
||||
* runtime, reads as "not seen yet" instead of "removed in Steam". "?" never matches, so nothing is dropped.
|
||||
*/
|
||||
private fun gridId(grid: File): String = runCatching {
|
||||
val f = File(grid, GRID_ID)
|
||||
f.takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: UUID.randomUUID().toString().also { id ->
|
||||
@@ -83,7 +76,6 @@ object SteamGrid {
|
||||
manifest.keys().asSequence().filter { name -> File(grid, name).let { it.isFile && it.length() == manifest.optLong(name, -1L) } }.toSet()
|
||||
}.getOrDefault(emptySet())
|
||||
|
||||
/** Puts a choice (or, with null, the lack of one) where Steam reads it, whether or not Steam is running. */
|
||||
fun write(context: Context, target: Target, slot: AddedGameArt.Slot, file: File?): Boolean = synchronized(lock) { place(context, target, slot, file) }
|
||||
|
||||
private fun place(context: Context, target: Target, slot: AddedGameArt.Slot, file: File?): Boolean {
|
||||
@@ -116,7 +108,6 @@ object SteamGrid {
|
||||
|
||||
private fun positionIn(file: File): LogoPosition.Value? = file.takeIf { it.isFile }?.let { runCatching { it.readText() }.getOrNull() }?.let(LogoPosition::parse)
|
||||
|
||||
/** The logo position chosen here (or taken over from Steam) for a game; null when Steam's own default applies. */
|
||||
fun position(target: Target): LogoPosition.Value? = positionIn(File(target.artDir, POSITION))
|
||||
|
||||
private fun positionRecorded(context: Context, grid: File, target: Target): String? =
|
||||
@@ -132,12 +123,10 @@ object SteamGrid {
|
||||
return runCatching { file.writeText(LogoPosition.toJson(value).toString()) }.isSuccess
|
||||
}
|
||||
|
||||
/** Sets (or with null, clears) a game's logo position here and in the client's grid folder, whether or not Steam is running. */
|
||||
fun writePosition(context: Context, target: Target, value: LogoPosition.Value?): Boolean = synchronized(lock) {
|
||||
placePosition(context, target, value) && storePosition(target, value)
|
||||
}
|
||||
|
||||
/** Steam keeps the position in `<id>.json`; anything else that file holds is left as it was. */
|
||||
private fun placePosition(context: Context, target: Target, value: LogoPosition.Value?): Boolean {
|
||||
val grid = dir(context) ?: return true
|
||||
val file = positionFile(grid, target.id)
|
||||
@@ -160,7 +149,6 @@ object SteamGrid {
|
||||
return true
|
||||
}
|
||||
|
||||
/** A `logoPosition` this version cannot read (a pin it does not know, say) is left alone rather than read as "removed". */
|
||||
private fun hasUnknownPosition(file: File): Boolean {
|
||||
val json = runCatching { JSONObject(file.readText()) }.getOrNull() ?: return false
|
||||
return json.has("logoPosition") && LogoPosition.parse(json) == null
|
||||
@@ -176,7 +164,6 @@ object SteamGrid {
|
||||
when {
|
||||
before == null && own != null && theirs == null -> placePosition(context, target, own)
|
||||
before == null || now != before -> {
|
||||
// Recorded only once the local side agrees, so a failed take-over is tried again on the next scan.
|
||||
if (theirs != null) {
|
||||
if (own == theirs || storePosition(target, theirs)) recordPosition(context, grid, target, now)
|
||||
} else {
|
||||
@@ -187,7 +174,6 @@ object SteamGrid {
|
||||
}
|
||||
}
|
||||
|
||||
/** Takes over what changed in Steam since the last look; returns true when a choice was added, replaced or dropped. */
|
||||
fun sync(context: Context, targets: List<Target>): Boolean = synchronized(lock) { reconcile(context, targets) }
|
||||
|
||||
private fun reconcile(context: Context, targets: List<Target>): Boolean {
|
||||
|
||||
@@ -70,15 +70,22 @@ object SteamGridDb {
|
||||
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
|
||||
}
|
||||
|
||||
fun gameId(key: String, steamAppId: Int?, name: String): Int? {
|
||||
fun gameId(key: String, steamAppId: Int?, name: String): Int? = gameId(key, steamAppId, name, ::match)
|
||||
|
||||
fun exactGameId(key: String, steamAppId: Int?, name: String): Int? = gameId(key, steamAppId, name, ::exactMatch)
|
||||
|
||||
private fun gameId(key: String, steamAppId: Int?, name: String, pick: (String, List<Pair<Int, String>>) -> Int?): Int? {
|
||||
if (steamAppId != null) {
|
||||
json(key, "$API/games/steam/$steamAppId")?.optJSONObject("data")?.optInt("id")?.takeIf { it > 0 }?.let { return it }
|
||||
}
|
||||
val term = URLEncoder.encode(name, "UTF-8").replace("+", "%20")
|
||||
val results = json(key, "$API/search/autocomplete/$term")?.optJSONArray("data") ?: return null
|
||||
return match(name, (0 until results.length()).map { results.getJSONObject(it) }.map { it.optInt("id") to it.optString("name") })
|
||||
return pick(name, (0 until results.length()).map { results.getJSONObject(it) }.map { it.optInt("id") to it.optString("name") })
|
||||
}
|
||||
|
||||
internal fun exactMatch(name: String, results: List<Pair<Int, String>>): Int? =
|
||||
results.firstOrNull { (id, got) -> id > 0 && AddedGameArt.nameMatch(name, got) == 3 }?.first
|
||||
|
||||
internal fun match(name: String, results: List<Pair<Int, String>>): Int? =
|
||||
results.map { (id, got) -> id to AddedGameArt.nameMatch(name, got) }
|
||||
.filter { it.second > 0 && it.first > 0 }
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.SteamLiveShortcuts
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
|
||||
object SteamLaunchOptions {
|
||||
private const val TAG = "SteamLaunchOptions"
|
||||
private val STEAM = listOf("UserLocalConfigStore", "Software", "Valve", "Steam")
|
||||
|
||||
fun current(context: Context, appId: Int): String =
|
||||
SteamLiveShortcuts.launchOptions(context, appId.toLong()) ?: steam(SessionPrefs.activeSteamRoot(context), appId).orEmpty()
|
||||
|
||||
enum class Saved { YES, NO, DESKTOP }
|
||||
|
||||
fun set(context: Context, appId: Int, options: String, shown: String): Saved {
|
||||
val value = options.trim()
|
||||
if (SessionState.running && SessionState.mode == SessionService.MODE_DESKTOP) return Saved.DESKTOP
|
||||
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) {
|
||||
val live = SteamLiveShortcuts.launchOptions(context, appId.toLong()) ?: return Saved.NO
|
||||
if (live.trim() != shown.trim()) return Saved.NO
|
||||
return if (SteamLiveShortcuts.setLaunchOptions(context, appId.toLong(), value)) Saved.YES else Saved.NO
|
||||
}
|
||||
val home = SessionPrefs.activeSteamRoot(context)
|
||||
if (steam(home, appId).orEmpty().trim() != shown.trim()) return Saved.NO
|
||||
return if (write(home, appId, value)) Saved.YES else Saved.NO
|
||||
}
|
||||
|
||||
internal fun steam(steamHome: File, appId: Int): String? {
|
||||
val config = AddedGames.accountConfig(steamHome) ?: return null
|
||||
val text = runCatching { File(config, "localconfig.vdf").readText() }.getOrNull() ?: return null
|
||||
return launchOptions(text, appId)
|
||||
}
|
||||
|
||||
internal fun write(steamHome: File, appId: Int, options: String): Boolean {
|
||||
val config = AddedGames.accountConfig(steamHome)?.let { File(it, "localconfig.vdf") } ?: return false
|
||||
val text = runCatching { config.readText() }.getOrNull() ?: return false
|
||||
val updated = withLaunchOptions(text, appId, options) ?: return false
|
||||
if (updated == text) return true
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
return try {
|
||||
staged.writeText(updated)
|
||||
if (config.readText() != text) {
|
||||
staged.delete()
|
||||
return false
|
||||
}
|
||||
Files.move(staged.toPath(), config.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not write launch options to ${config.path}", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
internal fun launchOptions(text: String, appId: Int): String? {
|
||||
val app = section(text, STEAM + "apps" + appId.toString()) ?: return null
|
||||
return entries(text, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals("LaunchOptions", true) }
|
||||
?.let { unescape(text.substring(it.valueStart + 1, it.end)) }
|
||||
}
|
||||
|
||||
internal fun withLaunchOptions(text: String, appId: Int, options: String): String? {
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
var updated = text
|
||||
var path = STEAM
|
||||
for (key in listOf("apps", appId.toString())) {
|
||||
updated = withSection(updated, section(updated, path) ?: return null, key, newline) ?: return null
|
||||
path = path + key
|
||||
}
|
||||
val app = section(updated, path) ?: return null
|
||||
val value = "\"" + escape(options) + "\""
|
||||
entries(updated, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals("LaunchOptions", true) }?.let {
|
||||
return updated.replaceRange(it.valueStart, it.end + 1, value)
|
||||
}
|
||||
val lineStart = closingLine(updated, app) ?: return null
|
||||
val indent = updated.substring(lineStart, app.end) + "\t"
|
||||
return updated.substring(0, lineStart) + indent + "\"LaunchOptions\"\t\t" + value + newline + updated.substring(lineStart)
|
||||
}
|
||||
|
||||
private class Entry(val key: String, val valueStart: Int, val end: Int, val section: Boolean)
|
||||
|
||||
private fun section(text: String, path: List<String>): Entry? {
|
||||
var found: Entry? = null
|
||||
for (key in path) {
|
||||
found = entries(text, found?.valueStart ?: -1, found?.end ?: text.length)
|
||||
.firstOrNull { it.section && it.key.equals(key, true) } ?: return null
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
private fun entries(text: String, open: Int, close: Int): List<Entry> {
|
||||
val found = ArrayList<Entry>()
|
||||
var key: String? = null
|
||||
var i = open + 1
|
||||
while (i < close) {
|
||||
when {
|
||||
text[i] == '"' -> {
|
||||
val end = stringEnd(text, i) ?: return found
|
||||
if (key == null) key = unescape(text.substring(i + 1, end)) else { found += Entry(key, i, end, false); key = null }
|
||||
i = end + 1
|
||||
}
|
||||
text[i] == '{' -> {
|
||||
val end = sectionEnd(text, i) ?: return found
|
||||
key?.let { found += Entry(it, i, end, true) }
|
||||
key = null
|
||||
i = end + 1
|
||||
}
|
||||
text.startsWith("//", i) -> i = text.indexOf('\n', i).let { if (it < 0) close else it }
|
||||
else -> i++
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
private fun stringEnd(text: String, open: Int): Int? {
|
||||
var i = open + 1
|
||||
while (i < text.length) {
|
||||
when (text[i]) {
|
||||
'\\' -> i += 2
|
||||
'"' -> return i
|
||||
else -> i++
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun sectionEnd(text: String, open: Int): Int? {
|
||||
var depth = 0
|
||||
var i = open
|
||||
while (i < text.length) {
|
||||
when (text[i]) {
|
||||
'"' -> i = stringEnd(text, i) ?: return null
|
||||
'{' -> depth++
|
||||
'}' -> if (--depth == 0) return i
|
||||
}
|
||||
i++
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun withSection(text: String, parent: Entry, key: String, newline: String): String? {
|
||||
if (entries(text, parent.valueStart, parent.end).any { it.section && it.key.equals(key, true) }) return text
|
||||
val lineStart = closingLine(text, parent) ?: return null
|
||||
val indent = text.substring(lineStart, parent.end) + "\t"
|
||||
return text.substring(0, lineStart) + "$indent\"$key\"$newline$indent{$newline$indent}$newline" + text.substring(lineStart)
|
||||
}
|
||||
|
||||
private fun closingLine(text: String, section: Entry): Int? {
|
||||
val lineStart = text.lastIndexOf('\n', section.end - 1) + 1
|
||||
return lineStart.takeIf { lineStart > section.valueStart && text.substring(lineStart, section.end).all { it == '\t' || it == ' ' } }
|
||||
}
|
||||
|
||||
private fun escape(value: String) = value.replace("\\", "\\\\").replace("\"", "\\\"")
|
||||
|
||||
private fun unescape(value: String) = value.replace(Regex("\\\\(.)"), "$1")
|
||||
}
|
||||
@@ -45,15 +45,15 @@ object SteamMatch {
|
||||
identity?.appId?.let { id ->
|
||||
return Match(id, Certainty.FILES, identity.source.name.lowercase(), now).also { put(context, key, it) }
|
||||
}
|
||||
val known = get(context, key)
|
||||
val known = get(context, key)?.takeUnless { it.appId == GameIdentifier.SPACEWAR }
|
||||
if (known != null && known.certainty == Certainty.NAME) return known
|
||||
if (known != null && known.certainty == Certainty.NONE && now - known.checkedAt < RETRY_AFTER_MS) return known
|
||||
legacy?.takeIf { it.isFile }?.let { runCatching { it.readText().trim().toInt() }.getOrNull() }?.takeIf { it > 0 }?.let { id ->
|
||||
legacy?.takeIf { it.isFile }?.let { runCatching { it.readText().trim().toInt() }.getOrNull() }?.takeIf { it > 0 && it != GameIdentifier.SPACEWAR }?.let { id ->
|
||||
return Match(id, Certainty.NAME, "store search", now).also { put(context, key, it) }
|
||||
}
|
||||
if (search == null) return known?.takeIf { it.certainty != Certainty.FILES } ?: Match(null, Certainty.NONE, "", 0)
|
||||
val id = runCatching { search(name) }.getOrNull()
|
||||
val match = if (id != null && id > 0) Match(id, Certainty.NAME, "store search", now) else Match(null, Certainty.NONE, "", now)
|
||||
val match = if (id != null && id > 0 && id != GameIdentifier.SPACEWAR) Match(id, Certainty.NAME, "store search", now) else Match(null, Certainty.NONE, "", now)
|
||||
put(context, key, match)
|
||||
return match
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ object SteamRedists {
|
||||
"228989" to ("vcredist2022_dll" to "VC++ 2022"),
|
||||
"228990" to ("d3dx9" to "DirectX (June 2010)"),
|
||||
)
|
||||
/** Redists a game's own install script runs on Windows that its shared depots don't name. */
|
||||
val SCRIPTED = mapOf(
|
||||
72850 to listOf("xact" to "DirectX XACT audio"),
|
||||
489830 to listOf("xact_x64" to "DirectX XACT audio (64-bit)"),
|
||||
@@ -28,7 +27,6 @@ object SteamRedists {
|
||||
return File(steamapps, "appmanifest_$appId.acf").takeIf { it.isFile }
|
||||
}
|
||||
|
||||
/** Redists the game's own install script has Steam run on Windows, from its "Run Process" entries. */
|
||||
fun installScript(gameDir: File?): List<Pair<String, String>> =
|
||||
gameDir?.listFiles { f ->
|
||||
f.isFile && f.length() < 1L shl 20 && f.name.lowercase().let { it.startsWith("installscript") && it.endsWith(".vdf") }
|
||||
|
||||
@@ -51,10 +51,8 @@ object WinCompSources {
|
||||
fun installer(path: String): List<String> = if (UE_PREREQ.containsMatchIn(path)) listOf("vcredist2022", "d3dx9") else DependencyDetector.componentsFor(path)
|
||||
|
||||
private val XBOX_KNOWN = Regex("""<KnownDependency\s+Name="([A-Za-z0-9_.-]{1,40})"""")
|
||||
// VC14 also registers the ARM64 runtime: launchers running as ARM64EC look for it and stop when it is missing.
|
||||
private val XBOX_COMPONENTS = mapOf("VC14" to listOf("vcredist2022", WinComponents.VCREDIST_ARM64))
|
||||
|
||||
/** Microsoft installs a PC Game Pass game's declared runtimes with it; VC14 is wanted by nearly all and is always added. */
|
||||
fun xbox(folder: File?): List<Pair<String, String>> {
|
||||
val config = folder?.listFiles().orEmpty().firstOrNull { it.isFile && it.name.equals("MicrosoftGame.config", ignoreCase = true) && it.length() < 1L shl 20 }
|
||||
val declared = config?.let { file -> runCatching { XBOX_KNOWN.findAll(file.readText()).map { it.groupValues[1] }.toList() }.getOrNull() }.orEmpty()
|
||||
|
||||
@@ -563,7 +563,6 @@ object Glasses {
|
||||
val device = selected?.first
|
||||
val m = selected?.second
|
||||
val controllable = m?.let(::canOpenModel) == true
|
||||
// XREAL uses Android's Ethernet sockets, without opening or claiming USB interfaces.
|
||||
val permitted = controllable && device != null && (m === XrealModel || usb.hasPermission(device))
|
||||
val identity = device?.let {
|
||||
GlassesModeState.Device(it.productId, if (permitted) runCatching { it.serialNumber }.getOrNull() else null)
|
||||
@@ -677,8 +676,6 @@ object Glasses {
|
||||
internal fun selectGlassesDisplay(displays: List<Display>, usbPresent: Boolean): Display? {
|
||||
val candidates = displays
|
||||
.filter { it.displayId != Display.DEFAULT_DISPLAY && it.flags and Display.FLAG_PRESENTATION != 0 }
|
||||
// Android can expose the glasses name on either the logical display or
|
||||
// its product metadata. A generic label on one must not hide the other.
|
||||
return candidates.firstOrNull { display ->
|
||||
isGlassesDisplayName(display.name) ||
|
||||
(Build.VERSION.SDK_INT >= 31 && display.deviceProductInfo?.let { product ->
|
||||
@@ -728,7 +725,6 @@ object Glasses {
|
||||
if (device.productId == VitureProtocol.PRO2_PRODUCT_ID) {
|
||||
VitureV2Link.open(usb, device, v2Listener(generation))
|
||||
} else if ((model as? VitureProtocol.Model)?.needsSdk == true) {
|
||||
// Android can evict cacheDir while the SDK is running.
|
||||
Log.i(TAG, "opening VITURE SDK pid=0x%04X spatial=%s".format(device.productId, spatial))
|
||||
VitureSdkLink.open(usb, device, File(app.noBackupFilesDir, "viture"), sdkListener(generation),
|
||||
(model as? VitureProtocol.Model)?.family, spatial)
|
||||
@@ -854,7 +850,6 @@ object Glasses {
|
||||
if (generation != linkGeneration) return@post
|
||||
closeLink()
|
||||
publish { it.copy(controlError = app.getString(R.string.glasses_connection_failed)) }
|
||||
// Let a reconnect or explicit Allow retry restart the SDK, not an endless failure loop.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -974,7 +969,6 @@ object Glasses {
|
||||
}
|
||||
if (!s.usable || s.sbs || modeState.pendingStereo) return
|
||||
val hz = _settings.value.refreshHz
|
||||
// Native 30 Hz is selected by the Android presentation, without a vendor mode command.
|
||||
if (hz == 30 && GlassesRendering.native30HzAvailable(_settings.value, s)) return
|
||||
if (glassesMode == m.mode(hz, false, outputResolution())) return
|
||||
if (!force) {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
/** Hardware properties; display refresh is selected from Android's advertised modes. */
|
||||
interface GlassesModel {
|
||||
val name: String
|
||||
val controllable: Boolean
|
||||
@@ -18,9 +17,6 @@ interface GlassesModel {
|
||||
fun modeForStep(step: Int): Int?
|
||||
}
|
||||
|
||||
/** The command IDs here are the existing glasses controller's internal vocabulary.
|
||||
* Each transport translates them to its own wire protocol; unsupported controls return false.
|
||||
*/
|
||||
internal interface GlassesLink {
|
||||
val hasImu: Boolean
|
||||
val badFrames: Long get() = 0L
|
||||
|
||||
@@ -63,7 +63,6 @@ class GlassesMenuSurface(
|
||||
override fun onDetachedFromWindow() {
|
||||
close()
|
||||
super.onDetachedFromWindow()
|
||||
// GLSurfaceView may exit its GL thread before queued cleanup is consumed.
|
||||
releaseInput()
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.glasses
|
||||
|
||||
import com.droiddeck.launcher.gpu.Cardboard
|
||||
|
||||
/** Share the actual picture mode with settings so controls match the rendered view. */
|
||||
internal object GlassesRendering {
|
||||
enum class Picture { FLAT, DUPLICATED, VIRTUAL_SCREEN, STEREO }
|
||||
|
||||
@@ -51,11 +50,7 @@ internal object GlassesRendering {
|
||||
outputActive: Boolean,
|
||||
steamVrRunning: Boolean,
|
||||
): Cardboard {
|
||||
// Mirror output still uses the glasses' picture and sensors during VR.
|
||||
if (!usesGlasses(state, outputActive, steamVrRunning)) {
|
||||
// SteamVR uses the renderer's enabled flag as headset proximity.
|
||||
// A flat phone preview still needs an active HMD and one SBS eye;
|
||||
// otherwise SteamVR enters standby and leaves a frozen frame.
|
||||
return if (steamVrRunning && !base.enabled) base.copy(
|
||||
enabled = true,
|
||||
source = Cardboard.SOURCE_SBS,
|
||||
|
||||
@@ -36,7 +36,6 @@ class GlassesScreen(context: Context, display: Display, refreshHz: Int, private
|
||||
fun prefer(hz: Int, resolution: GlassesResolution? = null) {
|
||||
wantHz = hz
|
||||
wantResolution = resolution
|
||||
// A 2D/SBS transition can replace the active mode without changing Hz.
|
||||
applyMode()
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,6 @@ internal class HandImageBuffer {
|
||||
pixels.clear()
|
||||
pixels.put(rgb)
|
||||
pixels.rewind()
|
||||
// MediaPipe applies the model metadata's float normalization to these RGB bytes.
|
||||
return ByteBufferImageBuilder(pixels, width, height, MPImage.IMAGE_FORMAT_RGB).build()
|
||||
}
|
||||
}
|
||||
@@ -150,7 +150,6 @@ class LumaRgbCaptureService : Service() {
|
||||
intent?.getIntExtra("durationMs",5000) ?: 5000) }
|
||||
finally {
|
||||
stopSelf()
|
||||
// SDK 2.4.0 can crash while cancelling failed USB transfers; isolate each diagnostic.
|
||||
android.os.Process.killProcess(android.os.Process.myPid())
|
||||
}
|
||||
}, "luma-rgb-diagnostic").start()
|
||||
|
||||
@@ -40,12 +40,9 @@ internal data class RayNeoCalibration(val gyroBiasDps: Vec3, val level: Quaterni
|
||||
|
||||
internal class RayNeoCalibrationStore(private val prefs: SharedPreferences) {
|
||||
companion object {
|
||||
// GT and GT Max can share USB identity fields. Keep the non-Max mounting
|
||||
// correction separate from existing Max profiles and their legacy keys.
|
||||
fun profileKey(base: String, gtUsb: Boolean, boardId: Int): String =
|
||||
if (gtUsb && boardId == RayNeoProtocol.BOARD_GT) "$base:gt-standard-v1" else base
|
||||
}
|
||||
// A serial isolates physical units. Devices without one share their model profile.
|
||||
fun key(vid: Int, pid: Int, serial: String?, modelName: String = ""): String =
|
||||
"rayneo-cal-v1:$vid:$pid:${serial?.takeIf { it.isNotBlank() } ?: "model:$modelName"}"
|
||||
fun load(key: String): RayNeoCalibration? = RayNeoCalibration.decode(prefs.getString(key, null))
|
||||
@@ -55,7 +52,6 @@ internal class RayNeoCalibrationStore(private val prefs: SharedPreferences) {
|
||||
}
|
||||
}
|
||||
|
||||
/** One upside-down stationary pose estimates gyro bias and tilt, never yaw or accelerometer scale. */
|
||||
internal class RayNeoCalibrationCollector(private val axes: RayNeoSensorAxes, private val beganMs: Long) {
|
||||
var phase = CalibrationPhase.SETTLING; private set
|
||||
var progress = 0; private set
|
||||
|
||||
@@ -6,7 +6,6 @@ import android.hardware.usb.UsbManager
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
|
||||
/** RayNeo command/response and IMU share one endpoint. Keep reads on a single worker. */
|
||||
internal class RayNeoLink private constructor(
|
||||
private val connection: UsbDeviceConnection,
|
||||
private val endpoints: RayNeoEndpointSelection,
|
||||
@@ -52,7 +51,6 @@ internal class RayNeoLink private constructor(
|
||||
ready && (mode == RayNeoProtocol.CMD_SWITCH_TO_3D || mode == RayNeoProtocol.CMD_SWITCH_TO_2D) &&
|
||||
command(mode)
|
||||
}
|
||||
// No VITURE brightness, volume, film, rate or raw command is sent to RayNeo.
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
@@ -159,7 +157,6 @@ internal class RayNeoLink private constructor(
|
||||
}
|
||||
val wxyz = filter.update(packet.sample)
|
||||
if (wantImu && collector == null && lastSensor >= warmupUntil) {
|
||||
// Normalize basis and component order at the hardware boundary.
|
||||
listener.onPose(raw, RayNeoOrientationFilter.glassesPose(wxyz),
|
||||
SystemClock.elapsedRealtimeNanos())
|
||||
}
|
||||
@@ -176,7 +173,6 @@ internal class RayNeoLink private constructor(
|
||||
override fun close() {
|
||||
synchronized(writeLock) {
|
||||
if (!running) return
|
||||
// Best effort: stop the sensor before releasing the claimed interface.
|
||||
if (ready) runCatching { command(RayNeoProtocol.CMD_CLOSE_IMU) }
|
||||
running = false
|
||||
}
|
||||
|
||||
@@ -8,8 +8,6 @@ object RayNeoModel {
|
||||
|
||||
fun model(vid: Int, pid: Int, name: String?): GlassesModel? {
|
||||
if (!isVendor(vid)) return null
|
||||
// GT's identity is confirmed by verncat's SDK; do not claim other products
|
||||
// from that vendor just because their name resembles a supported model.
|
||||
val gt = RayNeoProtocol.isGt(vid, pid)
|
||||
if (vid == RayNeoProtocol.GT_VENDOR_ID && !gt) return null
|
||||
if (!(vid == RayNeoProtocol.VENDOR_ID && pid == RayNeoProtocol.PRODUCT_ID) &&
|
||||
@@ -23,8 +21,6 @@ object RayNeoModel {
|
||||
name.contains("rayneo", ignoreCase = true) || name.contains("ray neo", ignoreCase = true) ||
|
||||
modelName.containsMatchIn(name)
|
||||
|
||||
// Observed on GT Max: Android exposes an unbranded EDID monitor name.
|
||||
// Match its product metadata, not every display called SmartGlasses/TCL.
|
||||
fun isDisplayProduct(name: String?, manufacturer: String?, productId: String?): Boolean =
|
||||
name?.trim().equals("SmartGlasses", ignoreCase = true) &&
|
||||
manufacturer.equals("TCL", ignoreCase = true) && productId == "980"
|
||||
@@ -33,7 +29,7 @@ object RayNeoModel {
|
||||
override val controllable = true
|
||||
override val brightnessMax = 0
|
||||
override val volumeMax = 0
|
||||
override val diagonalFovDeg = 46f // Conservative existing default, not a calibrated model profile.
|
||||
override val diagonalFovDeg = 46f
|
||||
override val sbs90 = false
|
||||
override fun mode(hz: Int, sbs: Boolean) =
|
||||
if (sbs) RayNeoProtocol.CMD_SWITCH_TO_3D else RayNeoProtocol.CMD_SWITCH_TO_2D
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// Adapted from informalTechCode/RayNeo-Air-Series-3DoF-Scaffold (Apache-2.0).
|
||||
// See docs/third-party/rayneo/. Returns scaffold quaternions in (w, x, y, z) order.
|
||||
// Adapted from informalTechCode/RayNeo-Air-Series-3DoF-Scaffold (Apache-2.0); see docs/third-party/rayneo/ for license and attribution.
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import kotlin.math.cos
|
||||
@@ -123,10 +122,6 @@ internal class RayNeoOrientationFilter(
|
||||
private var lastRealtimeNs: Long = 0L
|
||||
|
||||
companion object {
|
||||
/** Scaffold: right +X, up +Y, back +Z. VITURE: right -Y, up +Z, back -X.
|
||||
* Conjugate by HeadPose.GLASSES_AXES before entering the unchanged VITURE pose path.
|
||||
* This is a basis conversion, not a projection or seated-origin adjustment.
|
||||
*/
|
||||
fun glassesPose(wxyz: FloatArray): FloatArray =
|
||||
floatArrayOf(-wxyz[3], -wxyz[1], wxyz[2], wxyz[0])
|
||||
}
|
||||
@@ -168,8 +163,6 @@ internal class RayNeoOrientationFilter(
|
||||
if (accelNorm > 1e-3f) {
|
||||
val measuredUp = accel.normalized()
|
||||
if (!gravityInitialized) {
|
||||
// Align gravity before publishing the first pose. Starting at
|
||||
// identity and settling after recenter can rotate the horizon.
|
||||
val axis = measuredUp.cross(worldUp)
|
||||
q = if (measuredUp.y < -0.9999f) {
|
||||
Quaternion.fromAxisAngle(Vec3(1f, 0f, 0f), Math.PI.toFloat())
|
||||
@@ -179,7 +172,6 @@ internal class RayNeoOrientationFilter(
|
||||
gravityInitialized = true
|
||||
}
|
||||
val predictedUp = q.conjugate().rotate(worldUp).normalized()
|
||||
// q maps body to world: measured x predicted reduces gravity error.
|
||||
val correction = measuredUp.cross(predictedUp)
|
||||
gyro += correction * accelGain
|
||||
}
|
||||
|
||||
@@ -40,14 +40,13 @@ data class RayNeoEndpointSelection(
|
||||
object RayNeoProtocol {
|
||||
const val VENDOR_ID = 0x1BBB
|
||||
const val PRODUCT_ID = 0xAF50
|
||||
// verncat/RayNeo-Air-3S-Pro-OpenVR PR #3 (MIT), tested on GT hardware.
|
||||
const val GT_VENDOR_ID = 0x3941
|
||||
private const val GT_CONTROL_INTERFACE = 5
|
||||
|
||||
fun isGt(vid: Int, pid: Int) = vid == GT_VENDOR_ID && pid == PRODUCT_ID
|
||||
|
||||
const val BOARD_AIR_4_PRO = 0x3A
|
||||
const val BOARD_GT = 0x40 // Observed on the user's non-Max GT.
|
||||
const val BOARD_GT = 0x40
|
||||
|
||||
const val PKT_MAGIC = 0x99
|
||||
const val PKT_SENSOR = 0x65
|
||||
@@ -131,7 +130,6 @@ object RayNeoProtocol {
|
||||
endpoint.type != UsbConstants.USB_ENDPOINT_XFER_BULK) {
|
||||
continue
|
||||
}
|
||||
// Exclude small button reports from GT's protocol transport.
|
||||
if (gt && endpoint.maxPacketSize < 64) continue
|
||||
|
||||
if (endpoint.direction == UsbConstants.USB_DIR_IN && inEndpoint == null) {
|
||||
@@ -159,8 +157,6 @@ object RayNeoProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
// Interface numbers can change with firmware. Use a unique protocol-sized
|
||||
// pair when interface 5 is absent, never an arbitrary composite interface.
|
||||
return if (gt) gtCandidates.singleOrNull() else fallback
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import android.hardware.usb.UsbManager
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
|
||||
/** Controls are vendor control transfers; the HID interrupt endpoint streams IMU reports unprompted. */
|
||||
internal class RokidLink private constructor(
|
||||
private val connection: UsbDeviceConnection,
|
||||
private val usbInterface: UsbInterface,
|
||||
@@ -44,7 +43,7 @@ internal class RokidLink private constructor(
|
||||
?.let { listener.onValue(VitureProtocol.MSG_BRIGHTNESS, RokidModel.brightnessStep(it)) } != null
|
||||
VitureProtocol.MSG_BRIGHTNESS -> value in 0..RokidModel.BRIGHTNESS_STEPS &&
|
||||
control(RokidModel.REQUEST_SET_BRIGHTNESS, RokidModel.brightnessRaw(value), RokidModel.INDEX_BRIGHTNESS)
|
||||
else -> false // Volume is the glasses' USB audio device; there is no film or IMU-rate control.
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +53,6 @@ internal class RokidLink private constructor(
|
||||
if (!running) return null
|
||||
val buffer = ByteArray(64)
|
||||
val count = connection.controlTransfer(VENDOR_IN, request, 0, index, buffer, buffer.size, TIMEOUT_MS)
|
||||
// Display mode is reported in the second byte, brightness in the first.
|
||||
val offset = if (request == RokidModel.REQUEST_GET_DISPLAY) 1 else 0
|
||||
if (count > offset) buffer[offset].toInt() and 0xff else null
|
||||
}
|
||||
@@ -90,7 +88,6 @@ internal class RokidLink private constructor(
|
||||
if (enabled && !wasTracking) fusion = ImuFusion()
|
||||
wasTracking = enabled
|
||||
if (!enabled) continue
|
||||
// Max captures: already right/up/back; level gravity +Y, turn left +gyroY, look up +gyroX, roll right -gyroZ.
|
||||
fusion.update(sample.timeNs, sample.accel, sample.gyro)?.let {
|
||||
if (running && tracking) listener.onPose(buffer.copyOf(count), it, SystemClock.elapsedRealtimeNanos())
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.glasses
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/** Rokid Air/Max share one USB identity; Max 2 has a separate product ID. */
|
||||
internal class RokidModel private constructor(override val name: String, private val max: Boolean) : GlassesModel {
|
||||
override val controllable = true
|
||||
override val brightnessMax = BRIGHTNESS_STEPS
|
||||
@@ -36,7 +35,6 @@ internal class RokidModel private constructor(override val name: String, private
|
||||
const val MAX2_PRODUCT_ID = 0x2002
|
||||
const val BRIGHTNESS_STEPS = 10
|
||||
|
||||
// Vendor control requests, device recipient.
|
||||
const val REQUEST_SET_DISPLAY = 0x01
|
||||
const val REQUEST_GET_DISPLAY = 0x81
|
||||
const val REQUEST_SET_BRIGHTNESS = 0x02
|
||||
@@ -51,7 +49,6 @@ internal class RokidModel private constructor(override val name: String, private
|
||||
const val MODE_SBS_1200_60 = 5
|
||||
val MODES = setOf(MODE_2D_60, MODE_SBS_1080_60, MODE_2D_120, MODE_SBS_1200_90, MODE_SBS_1200_60)
|
||||
|
||||
// 0x04d2 is a shared vendor ID, so the Rokid product string is required too.
|
||||
fun model(vid: Int, pid: Int, name: String?): GlassesModel? {
|
||||
if (vid != VENDOR_ID || (pid != PRODUCT_ID && pid != MAX2_PRODUCT_ID)) return null
|
||||
val product = name?.trim()?.takeIf { it.startsWith("Rokid", ignoreCase = true) } ?: return null
|
||||
@@ -60,7 +57,6 @@ internal class RokidModel private constructor(override val name: String, private
|
||||
|
||||
fun isDisplay(name: String) = name.contains("Rokid", ignoreCase = true)
|
||||
|
||||
/** Device brightness is 0..100; the shared slider uses ten steps. */
|
||||
fun brightnessStep(raw: Int): Int = ((raw.coerceIn(0, 100) + 5) / 10).coerceIn(0, BRIGHTNESS_STEPS)
|
||||
fun brightnessRaw(step: Int): Int = step.coerceIn(0, BRIGHTNESS_STEPS) * 10
|
||||
}
|
||||
@@ -74,7 +70,6 @@ internal object RokidProtocol {
|
||||
private const val SENSOR_ACCEL = 1
|
||||
private const val SENSOR_GYRO = 2
|
||||
|
||||
/** Max sends one combined report; Air sends accel and gyro reports that share a timestamp. */
|
||||
class Parser {
|
||||
private var accel: Vec3? = null
|
||||
private var accelTime = -1L
|
||||
@@ -87,7 +82,7 @@ internal object RokidProtocol {
|
||||
return when (packet[0].toInt() and 0xff) {
|
||||
COMBINED -> Sample(b.getLong(1), vec(b, 9), vec(b, 21), packet[59].toInt() and 0xff)
|
||||
SEPARATE -> {
|
||||
val time = b.getLong(9) * 1000 // Air reports microseconds; Max reports nanoseconds.
|
||||
val time = b.getLong(9) * 1000
|
||||
when (packet[1].toInt() and 0xff) {
|
||||
SENSOR_ACCEL -> { accel = vec(b, 21); accelTime = time }
|
||||
SENSOR_GYRO -> { gyro = vec(b, 21); gyroTime = time }
|
||||
|
||||
@@ -26,7 +26,6 @@ internal class StereoCalibration(val identity: String, val width: Int, val heigh
|
||||
val source get() = if (bundledBase && !verified) "luma-ultra-base" else "device"
|
||||
private val p1 = Mat.zeros(3, 4, CvType.CV_64F)
|
||||
private val p2 = Mat.zeros(3, 4, CvType.CV_64F)
|
||||
private val undistortionMaps = Array(2) { arrayOf(Mat(),Mat()) }
|
||||
init {
|
||||
val a = Mat.eye(3, 4, CvType.CV_64F)
|
||||
val b = Mat.zeros(3, 4, CvType.CV_64F)
|
||||
@@ -35,18 +34,6 @@ internal class StereoCalibration(val identity: String, val width: Int, val heigh
|
||||
Core.gemm(k1, a, 1.0, empty, 0.0, p1); Core.gemm(k2, b, 1.0, empty, 0.0, p2)
|
||||
a.release(); b.release(); empty.release()
|
||||
}
|
||||
fun undistort(src: Mat, dst: Mat, right: Boolean) {
|
||||
val k = if (right) k2 else k1; val d = if (right) d2 else d1
|
||||
val maps=undistortionMaps[if(right) 1 else 0]
|
||||
if(maps[0].empty()) {
|
||||
val identity=Mat.eye(3,3,CvType.CV_64F)
|
||||
try {
|
||||
if(fisheye) Calib3d.fisheye_initUndistortRectifyMap(k,d,identity,k,src.size(),CvType.CV_16SC2,maps[0],maps[1])
|
||||
else Calib3d.initUndistortRectifyMap(k,d,identity,k,src.size(),CvType.CV_16SC2,maps[0],maps[1])
|
||||
} finally { identity.release() }
|
||||
}
|
||||
Imgproc.remap(src,dst,maps[0],maps[1],Imgproc.INTER_LINEAR)
|
||||
}
|
||||
fun triangulateRaw(left: List<Point>, right: List<Point>): List<SpatialVector>? {
|
||||
val points = triangulateLandmarksRaw(left,right) ?: return null
|
||||
return if(points.any { it == null }) null else points.filterNotNull()
|
||||
@@ -74,10 +61,6 @@ internal class StereoCalibration(val identity: String, val width: Int, val heigh
|
||||
return triangulatePoints(l.toList(),r.toList())
|
||||
} finally { l.release(); r.release(); identity.release() }
|
||||
}
|
||||
fun triangulate(left: List<Point>, right: List<Point>): List<SpatialVector>? {
|
||||
val points = triangulatePoints(left,right) ?: return null
|
||||
return if(points.any { it == null }) null else points.filterNotNull()
|
||||
}
|
||||
private fun triangulatePoints(left: List<Point>, right: List<Point>): List<SpatialVector?>? {
|
||||
if (left.size != right.size || left.isEmpty()) return null
|
||||
val a = Mat(2, left.size, CvType.CV_64F); val b = Mat(2, right.size, CvType.CV_64F); val out = Mat()
|
||||
@@ -105,7 +88,7 @@ internal class StereoCalibration(val identity: String, val width: Int, val heigh
|
||||
val tmp = File(file.parentFile,file.name+".tmp"); tmp.writeText(j.toString())
|
||||
java.nio.file.Files.move(tmp.toPath(),file.toPath(),java.nio.file.StandardCopyOption.REPLACE_EXISTING)
|
||||
}
|
||||
override fun close() { (listOf(k1,d1,k2,d2,r,t,p1,p2)+undistortionMaps.flatMap { it.toList() }).forEach { it.release() } }
|
||||
override fun close() { listOf(k1,d1,k2,d2,r,t,p1,p2).forEach { it.release() } }
|
||||
companion object {
|
||||
fun load(file: File, identity: String, width: Int, height: Int): StereoCalibration? =
|
||||
runCatching { StereoCalibrationProfile.parse(file.readText(), identity, width, height)?.let(::fromProfile) }.getOrNull()
|
||||
@@ -286,7 +269,6 @@ internal class StereoCalibrator(private val context: Context) : AutoCloseable {
|
||||
Mat().also { output -> corrected.add(output); Calib3d.fisheye_undistortPoints(pixels,output,k,d,identity,k) }
|
||||
}
|
||||
try {
|
||||
// OpenCV 4.13 fisheye stereo fitting assumes equal corner counts in every view.
|
||||
Calib3d.stereoCalibrate(objects,images(left,k1,d1),images(right,k2,d2),k1,if(fish)zero else d1,k2,if(fish)zero else d2,
|
||||
size,r,t,e,f,Calib3d.CALIB_FIX_INTRINSIC)
|
||||
} finally { (corrected+listOf(e,f,identity,zero)).forEach(Mat::release) }
|
||||
|
||||
@@ -383,7 +383,6 @@ internal class StereoHandEngine(private val context: Context, private val token:
|
||||
message=context.getString(R.string.spatial_frame_changed)
|
||||
calibrationProgress = calibrationProgress.copy(collecting = false, capturing = false, captureMessage = message)
|
||||
}
|
||||
// The callback pose's basis is undocumented; use canonical GL pose history.
|
||||
val observation=HandObservation(time,generation,trackingFrame)
|
||||
var captureHead=observation.headPose(SpatialTracking.session,metadata[6]>0)
|
||||
val w=metadata[0].toInt();val h=metadata[1].toInt()
|
||||
@@ -499,7 +498,6 @@ internal class StereoHandEngine(private val context: Context, private val token:
|
||||
dl=pair.first.hands;dr=pair.second.hands
|
||||
if(scheduled) inferenceSchedule.observe(stamp,dl.map { it.side },dr.map { it.side },pair.first.rawCount,pair.second.rawCount)
|
||||
val inferenceMs=(System.nanoTime()-inferenceStart)/1e6f
|
||||
// VIO callbacks can arrive during inference; verify this exact camera stamp before publishing.
|
||||
captureHead=observation.headPose(SpatialTracking.session,
|
||||
metadata[6]>0 || VitureSdk.nativeCameraSynchronized(token,metadata[2]))
|
||||
val hands=Array(2) { SpatialHand() }
|
||||
@@ -631,7 +629,7 @@ internal class StereoHandEngine(private val context: Context, private val token:
|
||||
SpatialTracking.publish(System.nanoTime())
|
||||
}
|
||||
}
|
||||
} catch(e: InterruptedException) { /* Shutdown interrupts the idle wait. */ }
|
||||
} catch(e: InterruptedException) { }
|
||||
catch(e: Throwable) {
|
||||
message=context.getString(R.string.spatial_hand_error, e.message.orEmpty())
|
||||
val unavailable=HandObservationDiagnostic(HandObservationOutcome.INFERENCE_UNAVAILABLE)
|
||||
|
||||
@@ -31,7 +31,6 @@ internal class StereoInferenceRunner : AutoCloseable {
|
||||
catch (e: ExecutionException) { throw e.cause ?: e }
|
||||
}
|
||||
} finally {
|
||||
// Native inference must finish before either camera's pixels or detector can be reused.
|
||||
if (interrupted) Thread.currentThread().interrupt()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,8 +12,6 @@ internal object UvcRgbDiagnostic {
|
||||
internal data class UvcStreamHealth(val observationMs: Double, val observedFps: Double,
|
||||
val maximumGapMs: Double, val healthy: Boolean) {
|
||||
companion object {
|
||||
// Health requires the full requested window, 80% of requested FPS, and no gap
|
||||
// (including the final silent interval) above max(250 ms, three frame periods).
|
||||
fun assess(metadata: LongArray, requestedFps: Int, durationMs: Int): UvcStreamHealth {
|
||||
require(metadata.size == 14 && requestedFps > 0 && durationMs > 0)
|
||||
val first = metadata[7]
|
||||
|
||||
@@ -81,7 +81,6 @@ object VitureProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
/** SDK validates the PID before returning this market name. Never guess a new PID. */
|
||||
fun sdkModel(marketName: String): Model? {
|
||||
val family = when (marketName) {
|
||||
"One", "Lite" -> Family.ONE
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.glasses
|
||||
import android.util.Log
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/** JNI adapter to VITURE's Android C SDK. The vendor binary is a local build input. */
|
||||
internal object VitureSdk {
|
||||
val available: Boolean by lazy {
|
||||
runCatching {
|
||||
@@ -27,7 +26,6 @@ internal object VitureSdk {
|
||||
external fun nativeSpatialDiagnostics(token: Long): DoubleArray?
|
||||
external fun nativeTracking(token: Long, enabled: Boolean): Int
|
||||
external fun nativeCommand(token: Long, command: Int, value: Int): Int
|
||||
/** Returns CLOCK_BOOTTIME receipt time, zero for no new pose, or a negative SDK error. */
|
||||
external fun nativePose(token: Long, wxyz: FloatArray): Long
|
||||
external fun nativeNextState(token: Long, event: IntArray): Int
|
||||
external fun nativeClose(token: Long)
|
||||
@@ -48,12 +46,9 @@ internal object VitureSpatialIdentity {
|
||||
}
|
||||
|
||||
internal object VitureSdkPose {
|
||||
// Pro 2 hardware captures use OpenGL axes despite the generic Gen2 callback's
|
||||
// NWU documentation. Keep that model-specific exception out of other Gen2 devices.
|
||||
fun usesOpenGlAxes(carina: Boolean, family: VitureProtocol.Family?) =
|
||||
carina || family == VitureProtocol.Family.PRO2
|
||||
|
||||
/** SDK quaternions are wxyz; normalize their coordinate basis at the boundary. */
|
||||
fun toGlasses(wxyz: FloatArray, openGlAxes: Boolean): FloatArray? {
|
||||
if (wxyz.size != 4 || wxyz.any { !it.isFinite() }) return null
|
||||
val length = sqrt(wxyz.sumOf { it.toDouble() * it }.toFloat())
|
||||
|
||||
@@ -7,7 +7,6 @@ import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
|
||||
/** SDK owns interface selection (including Ultra bulk endpoints) and all USB I/O. */
|
||||
internal class VitureSdkLink private constructor(
|
||||
private val connection: UsbDeviceConnection,
|
||||
private val token: Long,
|
||||
@@ -47,7 +46,6 @@ internal class VitureSdkLink private constructor(
|
||||
if (rc == 0 || !wanted) tracking = wanted
|
||||
return result("tracking", rc)
|
||||
}
|
||||
// Frequency is negotiated against SDK capabilities, including Pro 2's pose limit.
|
||||
VitureProtocol.MSG_IMU_RATE -> return tracking
|
||||
VitureProtocol.MSG_GET_IMU -> return true
|
||||
}
|
||||
@@ -89,7 +87,6 @@ internal class VitureSdkLink private constructor(
|
||||
if (VitureSdk.nativeNextState(token, event) == 1) when (event[0]) {
|
||||
0 -> listener.onValue(VitureProtocol.MSG_GET_BRIGHTNESS, event[1])
|
||||
1 -> listener.onValue(VitureProtocol.MSG_GET_VOLUME, event[1])
|
||||
// A device event can use a different display-mode namespace.
|
||||
2 -> send(VitureProtocol.MSG_GET_DISPLAY)
|
||||
3 -> listener.onValue(VitureProtocol.MSG_FILM, event[1])
|
||||
}
|
||||
@@ -122,7 +119,6 @@ internal class VitureSdkLink private constructor(
|
||||
if (!running) return
|
||||
running = false
|
||||
VitureSdk.nativeClose(token)
|
||||
// Keep Java's descriptor alive until the SDK and its worker threads have stopped.
|
||||
connection.close()
|
||||
}
|
||||
if (Thread.currentThread() !== worker) worker.join(1000)
|
||||
|
||||
@@ -69,7 +69,6 @@ internal class VitureV2Link internal constructor(
|
||||
return true
|
||||
}
|
||||
if (msgId == VitureProtocol.MSG_GET_IMU) return true
|
||||
// Keep the measured 120 Hz mode; the generic controller requests 240 Hz.
|
||||
if (msgId == VitureProtocol.MSG_IMU_RATE) return false
|
||||
val query = when (msgId) {
|
||||
VitureProtocol.MSG_GET_BRIGHTNESS -> VitureV2Protocol.MSG_GET_BRIGHTNESS
|
||||
@@ -146,9 +145,7 @@ internal class VitureV2Link internal constructor(
|
||||
tracking(true)
|
||||
if (becameReady) listener.onReady()
|
||||
val q = pose.quaternion
|
||||
// Upstream right/up/back pose converted to the shared VITURE legacy basis.
|
||||
val shared = floatArrayOf(-q[2], -q[0], q[1], q[3])
|
||||
// Upstream does not establish device tick units; use host monotonic receipt time.
|
||||
if (running && wanted && streamOn) listener.onPose(received.bytes, shared, received.timeNs)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// Adapted from elasticjava/viture-v2, MIT, Copyright (c) 2026 Holger Bartnick.
|
||||
// Source: ece8c30485f7d357fefa362ae74f3eabac9b3899; see docs/third-party/viture-v2/.
|
||||
// Adapted from elasticjava/viture-v2, MIT, Copyright (c) 2026 Holger Bartnick. Source: ece8c30485f7d357fefa362ae74f3eabac9b3899; see docs/third-party/viture-v2/.
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import kotlin.math.sqrt
|
||||
@@ -37,7 +36,6 @@ object VitureV2Protocol {
|
||||
val success: Boolean get() = status == 0
|
||||
}
|
||||
|
||||
// Device ticks have no established time unit; quaternion is xyzw with no axis remapping.
|
||||
class Pose internal constructor(
|
||||
val deviceTick: Long,
|
||||
val quaternion: FloatArray,
|
||||
@@ -64,7 +62,6 @@ object VitureV2Protocol {
|
||||
}
|
||||
|
||||
fun imuControl(streams: Int, rate: Rate = Rate.HZ_120): ByteArray {
|
||||
// Upstream measured that stream mask 3 ACKs but produces no events on Pro 2.
|
||||
require(streams == STREAM_OFF || streams == STREAM_POSE || streams == STREAM_RAW)
|
||||
require(streams != STREAM_POSE || rate.hz <= 240)
|
||||
val wireRate = if (streams == STREAM_OFF) 0 else rate.wireValue
|
||||
|
||||
@@ -24,7 +24,6 @@ internal interface XrealConnector : Closeable {
|
||||
|
||||
internal class XrealNetworkMissing : IOException("XREAL USB Ethernet network is not available")
|
||||
|
||||
/** Bind individual sockets, never the process: Steam must retain its Internet network. */
|
||||
internal class AndroidXrealConnector(context: Context) : XrealConnector {
|
||||
private val manager = context.getSystemService(ConnectivityManager::class.java)
|
||||
private val address = InetAddress.getByName(XrealProtocol.HOST)
|
||||
|
||||
@@ -7,7 +7,6 @@ import java.util.concurrent.ArrayBlockingQueue
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/** One connection owns two TCP channels. All control requests are serialized off the UI thread. */
|
||||
internal class XrealLink internal constructor(
|
||||
private val connector: XrealConnector,
|
||||
private val listener: Listener,
|
||||
@@ -47,7 +46,7 @@ internal class XrealLink internal constructor(
|
||||
VitureProtocol.MSG_DISPLAY -> value in 2..5 || value == XrealModel.NATIVE_60HZ
|
||||
VitureProtocol.MSG_BRIGHTNESS -> value in 0..9
|
||||
VitureProtocol.MSG_FILM -> value in 0..1
|
||||
else -> false // No guessed volume, sensor-rate, or VITURE wire commands.
|
||||
else -> false
|
||||
}
|
||||
return valid && commands.offer(Command(msgId, value))
|
||||
}
|
||||
@@ -88,7 +87,7 @@ internal class XrealLink internal constructor(
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
failure.set(e)
|
||||
current.close() // Wake a control read immediately.
|
||||
current.close()
|
||||
}
|
||||
}, "xreal-reports").apply { isDaemon = true; start() }
|
||||
ready = true
|
||||
@@ -145,12 +144,11 @@ internal class XrealLink internal constructor(
|
||||
tracking = false
|
||||
commands.clear()
|
||||
connection.getAndSet(null)?.close()
|
||||
connector.close() // Includes sockets still inside connect().
|
||||
connector.close()
|
||||
worker.interrupt()
|
||||
}
|
||||
}
|
||||
|
||||
/** Kept independent of Android so the real framing/acknowledgement path is testable. */
|
||||
internal class XrealControl(private val channels: XrealChannels, private val settleDelayMs: Long = 150) {
|
||||
private var transaction = 0
|
||||
private fun exchange(command: Int, value: Int? = null): ByteArray {
|
||||
@@ -158,7 +156,7 @@ internal class XrealControl(private val channels: XrealChannels, private val set
|
||||
channels.controlOutput.write(XrealProtocol.request(command, transaction, value))
|
||||
channels.controlOutput.flush()
|
||||
val deadline = System.nanoTime() + 3_000_000_000L
|
||||
repeat(32) { // Bound unsolicited button/status packets and stale responses.
|
||||
repeat(32) {
|
||||
if (System.nanoTime() > deadline) throw IOException("XREAL control timed out")
|
||||
XrealProtocol.response(XrealProtocol.read(channels.controlInput), command, transaction)?.let { return it }
|
||||
}
|
||||
@@ -172,9 +170,6 @@ internal class XrealControl(private val channels: XrealChannels, private val set
|
||||
fun changeDisplay(mode: Int): Int {
|
||||
val stereo = mode == 5
|
||||
set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0)
|
||||
// On 1S, SET_INPUT itself changes EDID. Sending SET_DISPLAY immediately
|
||||
// receives error 5001 while that change is pending. GET_DISPLAY returns
|
||||
// an empty property during the transition; wait for a real mode report.
|
||||
val current = awaitDisplay { (it == 5) == stereo }
|
||||
if (current == mode) return current
|
||||
set(XrealProtocol.SET_DISPLAY, mode)
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
/** First One-family target. Recovery and Air USB products must not use this transport. */
|
||||
object XrealModel : GlassesModel {
|
||||
const val VENDOR_ID = 0x3318
|
||||
const val PRODUCT_1S = 0x043e
|
||||
const val NATIVE_60HZ = 29 // Captured on 1S: 1920 x 1200 at 60 Hz.
|
||||
const val NATIVE_60HZ = 29
|
||||
override val name = "XREAL 1S"
|
||||
override val controllable = true
|
||||
override val brightnessMax = 9
|
||||
@@ -16,7 +15,6 @@ object XrealModel : GlassesModel {
|
||||
fun matches(vid: Int, pid: Int) = vid == VENDOR_ID && pid == PRODUCT_1S
|
||||
fun isDisplay(name: String) = name.contains("XREAL", ignoreCase = true)
|
||||
|
||||
// One-family EDID configuration values, not VITURE's display mode IDs.
|
||||
override fun mode(hz: Int, sbs: Boolean) = when {
|
||||
sbs -> 5
|
||||
hz >= 120 -> 4
|
||||
|
||||
@@ -2,19 +2,14 @@ package com.droiddeck.launcher.glasses
|
||||
|
||||
import kotlin.math.abs
|
||||
|
||||
/** 1S radians/sec and device nanoseconds, mapped using directed hardware captures. */
|
||||
internal class XrealOrientationFilter {
|
||||
private val fusion = ImuFusion()
|
||||
|
||||
// 1S reports right/down/forward. Rotate 180 degrees about X into the
|
||||
// shared right/up/back basis before either gravity alignment or fusion.
|
||||
// Captures: level gravity -Y; looking left -gyroY; up +gyroX; right tilt +gyroZ.
|
||||
fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs,
|
||||
Vec3(sample.accel.x, -sample.accel.y, -sample.accel.z),
|
||||
Vec3(sample.gyro.x, -sample.gyro.y, -sample.gyro.z))
|
||||
}
|
||||
|
||||
/** Gyro integration with gravity correction in the shared right/up/back basis, rad/s and device ns. */
|
||||
internal class ImuFusion {
|
||||
private var previous = 0L
|
||||
private var rotation = Quaternion.IDENTITY
|
||||
@@ -27,7 +22,7 @@ internal class ImuFusion {
|
||||
previous = timeNs
|
||||
val norm = accel.length()
|
||||
val gravityValid = abs(norm - 9.81f) < 1.5f
|
||||
if (dt > 0.25f) initialized = false // Never integrate a reconnect/stall as motion.
|
||||
if (dt > 0.25f) initialized = false
|
||||
if (!initialized) {
|
||||
if (!gravityValid) return null
|
||||
val up = accel.normalized()
|
||||
@@ -47,7 +42,6 @@ internal class ImuFusion {
|
||||
}
|
||||
rotation = rotation.integrateBodyRate(rate, dt).normalized()
|
||||
}
|
||||
// Same right/up/back -> shared glasses basis used by the RayNeo adapter.
|
||||
return RayNeoOrientationFilter.glassesPose(floatArrayOf(rotation.w, rotation.x, rotation.y, rotation.z))
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import java.io.InputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/** Independent implementation of the One-family wire format; see xreal-investigation.md. */
|
||||
internal object XrealProtocol {
|
||||
const val HOST = "169.254.2.1"
|
||||
const val REPORT_PORT = 52998
|
||||
@@ -46,7 +45,7 @@ internal object XrealProtocol {
|
||||
fun sample(frame: Frame): Sample? {
|
||||
if (frame.command != REPORT || frame.body.size != 128) return null
|
||||
val b = ByteBuffer.wrap(frame.body).order(ByteOrder.LITTLE_ENDIAN)
|
||||
if (b.getInt(24) != 11) return null // Magnetometer reports are a different type.
|
||||
if (b.getInt(24) != 11) return null
|
||||
val time = b.getLong(8)
|
||||
val gyro = Vec3(b.getFloat(28), b.getFloat(32), b.getFloat(36))
|
||||
val accel = Vec3(b.getFloat(40), b.getFloat(44), b.getFloat(48))
|
||||
@@ -64,7 +63,6 @@ internal object XrealProtocol {
|
||||
.putInt(4 + payload.size).putInt(transaction or Int.MIN_VALUE).put(payload).array()
|
||||
}
|
||||
|
||||
/** No acknowledgement is inferred from a write; match both command and transaction. */
|
||||
fun response(frame: Frame, command: Int, transaction: Int): ByteArray? {
|
||||
if (frame.command != command || frame.body.size < 4 ||
|
||||
ByteBuffer.wrap(frame.body).int != transaction) return null
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.DeviceSupport
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import java.io.File
|
||||
|
||||
data class AppVulkan(
|
||||
val major: Int,
|
||||
val minor: Int,
|
||||
val shaderInt64: Boolean?,
|
||||
val maxPushConstants: Int?,
|
||||
val source: String,
|
||||
) {
|
||||
fun atLeast(major: Int, minor: Int): Boolean = this.major > major || (this.major == major && this.minor >= minor)
|
||||
|
||||
val label: String
|
||||
get() = "Vulkan $major.$minor, shaderInt64 ${shaderInt64?.let { if (it) "yes" else "no" } ?: "?"}, " +
|
||||
"push constants ${maxPushConstants ?: "?"} ($source)"
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AppVulkan"
|
||||
const val BRIDGE_FILE = "apps-vulkan"
|
||||
|
||||
fun detect(context: Context): AppVulkan? {
|
||||
if (!DeviceSupport.vkBridge(context)) return null
|
||||
val native = VulkanInfo.query()
|
||||
val file = File(VkBridgeComponent.cacheDir(context), BRIDGE_FILE)
|
||||
val fromBridge = FileUtils.readString(file)?.let { fromBridgeFile(it, native["device"], native["api"]) }
|
||||
val found = fromBridge ?: fromDriver(native)
|
||||
Log.i(TAG, found?.label ?: "unknown (driver query: ${native["error"] ?: "no api line"})")
|
||||
return found
|
||||
}
|
||||
|
||||
internal fun fromBridgeFile(text: String, driverDevice: String?, driverApi: String? = null): AppVulkan? {
|
||||
val map = keyValues(text)
|
||||
val device = map["device"]
|
||||
if (device != null && driverDevice != null && device != driverDevice) return null
|
||||
val fileDriver = version(map["driver_api"])
|
||||
val native = version(driverApi)
|
||||
if (fileDriver != null && native != null && fileDriver != native) return null
|
||||
val promoted = map["promotion"]?.trim()?.lowercase() == "on"
|
||||
val (major, minor) = (if (promoted) version(map["api"]) else fileDriver ?: version(map["api"])) ?: return null
|
||||
return AppVulkan(major, minor, bool(map["shader_int64"]), map["max_push_constants"]?.toIntOrNull(),
|
||||
if (promoted) "bridge, promoted" else "bridge")
|
||||
}
|
||||
|
||||
internal fun fromDriver(map: Map<String, String>): AppVulkan? {
|
||||
val (major, minor) = version(map["api"]) ?: return null
|
||||
return AppVulkan(major, minor, bool(map["shader_int64"]), map["max_push_constants"]?.toIntOrNull(), "driver")
|
||||
}
|
||||
|
||||
private fun keyValues(text: String): Map<String, String> = text.lineSequence().mapNotNull { line ->
|
||||
val eq = line.indexOf('=')
|
||||
if (eq <= 0) null else line.substring(0, eq).trim() to line.substring(eq + 1).trim()
|
||||
}.toMap()
|
||||
|
||||
private fun version(v: String?): Pair<Int, Int>? {
|
||||
val parts = v?.trim()?.split('.') ?: return null
|
||||
if (parts.size < 2) return null
|
||||
val major = parts[0].toIntOrNull() ?: return null
|
||||
val minor = parts[1].toIntOrNull() ?: return null
|
||||
return major to minor
|
||||
}
|
||||
|
||||
private fun bool(v: String?): Boolean? = when (v?.trim()?.lowercase()) {
|
||||
"1", "yes", "true" -> true
|
||||
"0", "no", "false" -> false
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,10 +48,6 @@ object AutoDriverTrial {
|
||||
|
||||
fun bad(context: Context): Set<String> = prefs(context).getStringSet("bad", emptySet()).orEmpty()
|
||||
|
||||
/**
|
||||
* Counted before the compositor loads the trial display driver, so a driver that kills the process during
|
||||
* Vulkan init still counts towards a rollback; sessionStarting runs too late for that.
|
||||
*/
|
||||
fun displayStarting(context: Context, display: String) {
|
||||
val p = prefs(context)
|
||||
if (p.getString("release", null) == null || p.getString("display", "") != display) return
|
||||
|
||||
@@ -29,9 +29,10 @@ object AutoPicks {
|
||||
val BUILT_IN = listOf(
|
||||
Rule(setOf(Family.A8XX), models = setOf(840), prefer = listOf(NEWEST_DD_TURNIP, DriverPairs.WN_BALANCED)),
|
||||
Rule(setOf(Family.A8XX), prefer = listOf(DriverPairs.WN_BALANCED)),
|
||||
Rule(setOf(Family.A7XX_LOW), prefer = listOf(DriverPairs.BANNER_710)),
|
||||
Rule(setOf(Family.A7XX_LOW), prefer = listOf(NEWEST_DD_TURNIP, DriverPairs.BANNER_710)),
|
||||
Rule(setOf(Family.A7XX), oneUi8Gen2 = true, prefer = listOf(DriverPairs.BANNER_ONEUI)),
|
||||
Rule(setOf(Family.A7XX, Family.A6XX), prefer = listOf(DriverPairs.BANNER)),
|
||||
Rule(setOf(Family.A7XX), prefer = listOf(NEWEST_DD_TURNIP, DriverPairs.BANNER)),
|
||||
Rule(setOf(Family.A6XX), prefer = listOf(DriverPairs.BANNER)),
|
||||
Rule(setOf(Family.ADRENO_UNKNOWN), minSdk = 36, prefer = listOf(DriverPairs.WN_BALANCED)),
|
||||
Rule(setOf(Family.ADRENO_UNKNOWN), prefer = listOf(DriverPairs.BANNER)),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.PowerManager
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
import java.io.FileWriter
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
class ClockLogComponent(private val logFile: File) : SessionPart() {
|
||||
@Volatile private var running = false
|
||||
private var thread: Thread? = null
|
||||
|
||||
override fun start() {
|
||||
running = true
|
||||
thread = Thread({ run() }, "clock-log").apply { isDaemon = true; start() }
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
running = false
|
||||
thread?.interrupt()
|
||||
thread = null
|
||||
}
|
||||
|
||||
private fun run() {
|
||||
val policies = File("/sys/devices/system/cpu/cpufreq").listFiles { f -> f.name.startsWith("policy") }
|
||||
?.sortedBy { it.name.removePrefix("policy").toIntOrNull() ?: 0 } ?: emptyList()
|
||||
val gpuCandidates = gpuSources()
|
||||
val gpu = gpuCandidates.firstOrNull { !it.startsWith("/proc/") && firstNumber(it) != null }
|
||||
val power = app().getSystemService(Context.POWER_SERVICE) as? PowerManager
|
||||
val time = SimpleDateFormat("HH:mm:ss", Locale.US)
|
||||
try {
|
||||
FileWriter(logFile, true).use { w ->
|
||||
w.write("== clocks: ${Build.MANUFACTURER} ${Build.MODEL} (${Build.HARDWARE}), every ${PERIOD_MS / 1000}s\n")
|
||||
w.write("cpu policies: ${policies.joinToString { p -> p.name + " " + (File(p, "related_cpus").readTextOrNull()?.trim() ?: "?") }}\n")
|
||||
for (source in gpuCandidates) {
|
||||
val f = File(source)
|
||||
val state = when {
|
||||
!f.exists() -> continue
|
||||
firstNumber(source) != null -> "readable"
|
||||
else -> "refused"
|
||||
}
|
||||
w.write("gpu source $source: $state\n")
|
||||
}
|
||||
w.write("gpu clock from: ${gpu ?: "nothing readable"}\n")
|
||||
w.flush()
|
||||
while (running && logFile.length() < MAX_BYTES) {
|
||||
val line = StringBuilder(time.format(Date()))
|
||||
for (p in policies) {
|
||||
val cur = firstNumber(File(p, "scaling_cur_freq").path)
|
||||
val max = firstNumber(File(p, "scaling_max_freq").path)
|
||||
val hw = firstNumber(File(p, "cpuinfo_max_freq").path)
|
||||
line.append(" ${p.name.removePrefix("policy").let { "p$it" }} ${mhz(cur)}/${mhz(max)}")
|
||||
if (hw != null && max != null && max < hw) line.append("(of ${mhz(hw)})")
|
||||
}
|
||||
gpu?.let { line.append(" | gpu ${mhz(firstNumber(it))} MHz") }
|
||||
if (power != null && Build.VERSION.SDK_INT >= 29) {
|
||||
line.append(" | thermal ${power.currentThermalStatus}")
|
||||
if (Build.VERSION.SDK_INT >= 30) {
|
||||
val h = power.getThermalHeadroom(10)
|
||||
if (!h.isNaN()) line.append(String.format(Locale.US, " headroom %.2f", h))
|
||||
}
|
||||
}
|
||||
w.write(line.append('\n').toString())
|
||||
w.flush()
|
||||
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "clock log stopped: $e")
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
private const val PERIOD_MS = 2000L
|
||||
private const val MAX_BYTES = 4L shl 20
|
||||
|
||||
private fun gpuSources(): List<String> {
|
||||
val list = mutableListOf(
|
||||
"/sys/kernel/ged/hal/current_freqency", "/sys/kernel/ged/hal/current_frequency",
|
||||
"/proc/gpufreqv2/gpufreq_status", "/proc/gpufreq/gpufreq_var_dump",
|
||||
"/sys/kernel/gpu/gpu_clock", "/sys/class/misc/mali0/device/cur_freq",
|
||||
"/sys/class/misc/mali0/device/clock",
|
||||
)
|
||||
File("/sys/class/devfreq").list()?.sorted()?.forEach { node ->
|
||||
if (node.contains("mali", true) || node.contains("gpu", true)) list.add("/sys/class/devfreq/$node/cur_freq")
|
||||
}
|
||||
return list.distinct()
|
||||
}
|
||||
|
||||
private fun File.readTextOrNull(): String? = runCatching { readText() }.getOrNull()
|
||||
|
||||
private fun firstNumber(path: String): Long? =
|
||||
runCatching { Regex("\\d+").find(File(path).readText())?.value?.toLong() }.getOrNull()
|
||||
|
||||
private fun mhz(raw: Long?): String = when {
|
||||
raw == null -> "?"
|
||||
raw > 10_000_000 -> (raw / 1_000_000).toString()
|
||||
raw > 10_000 -> (raw / 1_000).toString()
|
||||
else -> raw.toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ object DeviceInfo {
|
||||
val vk = VulkanInfo.query()
|
||||
val gpu = GpuInfo.detect()
|
||||
return listOf(
|
||||
chip(), gpu(gpu), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
|
||||
chip(), gpu(context, gpu), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
|
||||
).filter { it.rows.isNotEmpty() }
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ object DeviceInfo {
|
||||
add("Family", read("/sys/devices/soc0/family"))
|
||||
})
|
||||
|
||||
private fun gpu(gpu: GpuInfo) = Section("GPU", buildList<Pair<String, String>> {
|
||||
private fun gpu(context: Context, gpu: GpuInfo) = Section("GPU", buildList<Pair<String, String>> {
|
||||
add("GPU", gpu.name)
|
||||
add("Family", gpu.family.label)
|
||||
add("Model found from", when (gpu.modelSource) {
|
||||
@@ -66,7 +66,7 @@ object DeviceInfo {
|
||||
add("Clock range", gpuRange())
|
||||
add("Load", read("$kgsl/gpu_busy_percentage")?.let { if (it.endsWith("%")) it else "$it %" })
|
||||
add("Temperature", read("$kgsl/temp")?.toLongOrNull()?.let { if (it > 1000) "${it / 1000} °C" else "$it °C" })
|
||||
add("Support", gpu.supportText)
|
||||
add("Support", gpu.supportText(SessionPrefs.vkBridge(context)))
|
||||
})
|
||||
|
||||
private fun cpu() = Section("CPU", buildList<Pair<String, String>> {
|
||||
|
||||
@@ -52,7 +52,6 @@ object FrameGen {
|
||||
|
||||
fun apply(context: Context, refreshHz: Float): String? = apply(context, mode(context), refreshHz)
|
||||
|
||||
/** Arms [mode] in this process's compositor; the cloud player passes its own mode and frame-rate cap. */
|
||||
fun apply(context: Context, mode: Mode, refreshHz: Float): String? {
|
||||
when (mode.engine) {
|
||||
ENGINE_LSFG -> {
|
||||
|
||||
@@ -53,6 +53,18 @@ data class GpuInfo(
|
||||
Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
|
||||
}
|
||||
|
||||
fun supportText(bridge: Boolean): String = when {
|
||||
support != Support.UNSUPPORTED -> supportText
|
||||
bridge -> "Runs through the Mali bridge, on the phone's own Vulkan driver"
|
||||
else -> "Not supported with the Mali bridge off: Turnip needs an Adreno (Snapdragon) GPU"
|
||||
}
|
||||
|
||||
fun supportText(context: Context, bridge: Boolean): String = when {
|
||||
support != Support.UNSUPPORTED -> supportText(context)
|
||||
bridge -> context.getString(R.string.gpuinfo_bridge)
|
||||
else -> context.getString(R.string.gpuinfo_bridge_off)
|
||||
}
|
||||
|
||||
fun supportText(context: Context): String = context.getString(when (support) {
|
||||
Support.TESTED -> R.string.gpuinfo_supported
|
||||
Support.UNTESTED -> when {
|
||||
|
||||
@@ -25,14 +25,6 @@ public final class LinuxVulkanDriver {
|
||||
return values;
|
||||
}
|
||||
|
||||
public static String optionLabel(Context context, String value) {
|
||||
if (value == null || value.isEmpty()) return "Runtime default (built into the runtime)";
|
||||
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
|
||||
if (!m.isInstalled(value)) return value + " (imported, missing - uses the runtime default)";
|
||||
String ver = m.getDriverVersion(value);
|
||||
return m.getDriverName(value) + (ver.isEmpty() ? "" : " " + ver) + " (imported)";
|
||||
}
|
||||
|
||||
public static String resolveIcdPath(Context context, String value) {
|
||||
if (value == null || value.isEmpty()) return null;
|
||||
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
|
||||
|
||||
@@ -6,7 +6,6 @@ import java.io.RandomAccessFile
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.attribute.BasicFileAttributes
|
||||
|
||||
/** Only new compositor output is evidence of a fault in the current session. */
|
||||
internal class SteamVrDeviceLossLog(private val file: File) {
|
||||
private var identity: Any? = identity()
|
||||
private var position = file.length()
|
||||
@@ -34,7 +33,6 @@ internal class SteamVrDeviceLossLog(private val file: File) {
|
||||
}
|
||||
identity = current
|
||||
prefix = head
|
||||
// Fault loops can produce megabytes per second. Bound work and keep the newest output.
|
||||
if (input.length() - position > MAX_READ) {
|
||||
position = input.length() - MAX_READ
|
||||
partial = ""
|
||||
|
||||
@@ -11,7 +11,6 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.SessionEvents
|
||||
import java.io.File
|
||||
|
||||
/** Process-wide cursor survives Activity recreation; a new session ignores older log errors. */
|
||||
internal object SteamVrHealth {
|
||||
private var session: String? = null
|
||||
private var log: SteamVrDeviceLossLog? = null
|
||||
@@ -49,7 +48,6 @@ internal class SteamVrRecovery(private val activity: Activity, private val foreg
|
||||
.create()
|
||||
prompt.setOnDismissListener { countdown?.let(handler::removeCallbacks); countdown = null; dialog = null }
|
||||
dialog = prompt
|
||||
// A touch meant for the game must not silently dismiss the recovery controls.
|
||||
prompt.setCanceledOnTouchOutside(false)
|
||||
prompt.show()
|
||||
if (automatic) {
|
||||
@@ -66,7 +64,6 @@ internal class SteamVrRecovery(private val activity: Activity, private val foreg
|
||||
|
||||
private fun restart() {
|
||||
if (!foreground()) return
|
||||
// Commit before crossing processes so a repeated fault cannot create a restart loop.
|
||||
if (!activity.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
||||
.putLong(LAST_ATTEMPT, System.currentTimeMillis()).commit()) return
|
||||
SessionEvents.record("steamvr.recovery_requested")
|
||||
|
||||
@@ -5,13 +5,11 @@ import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
internal object SteamVrRecoverySettings {
|
||||
/** After a graphics crash SteamVR can quarantine our HMD, leaving a server with no VR output. */
|
||||
fun unblockHeadset(file: File): Boolean {
|
||||
if (!file.isFile) return false
|
||||
val settings = JSONObject(file.readText())
|
||||
val driver = settings.optJSONObject("driver_droiddeck") ?: return false
|
||||
if (!driver.optBoolean("blocked_by_safe_mode")) return false
|
||||
// Preserve every other setting, including safe mode and blocks on other drivers.
|
||||
driver.put("blocked_by_safe_mode", false)
|
||||
val atomic = AtomicFile(file)
|
||||
val output = atomic.startWrite()
|
||||
|
||||
@@ -14,7 +14,6 @@ import com.droiddeck.launcher.SessionActivity
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import org.json.JSONObject
|
||||
|
||||
/** A visible, private process survives destruction of the app's native graphics context. */
|
||||
class SteamVrRestartActivity : Activity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
@@ -41,7 +40,6 @@ class SteamVrRestartActivity : Activity() {
|
||||
}, SystemClock::elapsedRealtime, SystemClock::sleep)
|
||||
if (shutdown != SteamVrRecoveryPolicy.Shutdown.COMPLETE)
|
||||
android.util.Log.w("SteamVrRecovery", "Restarting before the session finished stopping: $shutdown")
|
||||
// Only the verified main process, never a caller-supplied PID or an external app.
|
||||
Process.killProcess(main.pid)
|
||||
val exited = SystemClock.elapsedRealtime() + 5000
|
||||
while (java.io.File("/proc/${main.pid}").exists() && SystemClock.elapsedRealtime() < exited) SystemClock.sleep(50)
|
||||
|
||||
@@ -13,9 +13,6 @@ object TpUbwcHint {
|
||||
@Volatile var activeMode: String? = null
|
||||
private set
|
||||
|
||||
// On Adreno 740, TPL1_DBG_ECO_CNTL1.TP_UBWC_FLAG_HINT is shared by every driver on the GPU and must
|
||||
// match the system driver. A mismatch corrupts Android UI.
|
||||
// Samsung's One UI firmware sets it whatever blob version it reports.
|
||||
internal fun features(model: Int, systemDriverVersion: String?, samsung: Boolean = false,
|
||||
mode: String = SessionPrefs.TP_UBWC_AUTO): String? {
|
||||
if (model != 740) return null
|
||||
|
||||
@@ -291,6 +291,10 @@ public final class TurnipDriver {
|
||||
}
|
||||
String quest = QuestExperimental.INSTANCE.defaultAndroidDriver();
|
||||
if (quest != null) return quest;
|
||||
if (com.droiddeck.launcher.core.DeviceSupport.INSTANCE.vkBridge(context)) {
|
||||
Log.i(TAG, "Mali bridge: the compositor uses the system Vulkan driver");
|
||||
return null;
|
||||
}
|
||||
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");
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Process
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.HostProcess
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
|
||||
class VkBridgeComponent(private val socket: File, private val logFile: File) : SessionPart() {
|
||||
@Volatile private var pid = -1
|
||||
@Volatile private var exited = false
|
||||
|
||||
override fun start() {
|
||||
stop()
|
||||
val binary = File(app().applicationInfo.nativeLibraryDir, BINARY)
|
||||
if (!binary.isFile) {
|
||||
Log.e(TAG, "server missing at $binary; the session will have no Vulkan")
|
||||
return
|
||||
}
|
||||
socket.parentFile?.mkdirs()
|
||||
val cacheDir = cacheDir(app())
|
||||
writeMode(cacheDir, com.droiddeck.launcher.session.SessionPrefs.vkBridgeMode(app()))
|
||||
if (VkBridgeNative.start(app(), socket, logFile, cacheDir)) {
|
||||
Log.i(TAG, "server ready in the app's process at $socket")
|
||||
return
|
||||
}
|
||||
socket.delete()
|
||||
exited = false
|
||||
val cmd = listOf(binary.absolutePath, "--socket", socket.absolutePath, "--log", logFile.absolutePath,
|
||||
"--cache-dir", cacheDir.absolutePath)
|
||||
.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
|
||||
val env = arrayOf("HOME=" + app().filesDir)
|
||||
pid = HostProcess.start(cmd, env, app().filesDir, { status ->
|
||||
exited = true
|
||||
Log.w(TAG, "server exited with status $status")
|
||||
runCatching { logFile.appendText("== vkbridge server exited with status $status\n") }
|
||||
}, { line -> Log.i(TAG, line) })
|
||||
val began = System.currentTimeMillis()
|
||||
val deadline = began + 15_000L
|
||||
while (!socket.exists() && !exited && System.currentTimeMillis() < deadline) {
|
||||
try { Thread.sleep(50L) } catch (e: InterruptedException) { Thread.currentThread().interrupt(); break }
|
||||
}
|
||||
val waited = System.currentTimeMillis() - began
|
||||
Log.i(TAG, if (socket.exists()) "server ready (pid $pid) at $socket after $waited ms"
|
||||
else "server NOT ready (pid $pid, exited=$exited) after $waited ms; see $logFile")
|
||||
if (!socket.exists() && VkBridgeNative.start(app(), socket, logFile, cacheDir)) Log.i(TAG, "server ready in the app's process at $socket")
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
if (pid > 0) {
|
||||
Process.killProcess(pid)
|
||||
pid = -1
|
||||
}
|
||||
if (!VkBridgeNative.serving) socket.delete()
|
||||
}
|
||||
|
||||
override fun suspendPid(): Int = pid
|
||||
|
||||
companion object {
|
||||
private const val TAG = "VkBridge"
|
||||
private const val CACHE_DIR = "vkbridge-pipelines"
|
||||
private const val MODE_FILE = "mode"
|
||||
|
||||
fun cacheDir(context: Context): File {
|
||||
val dir = File(context.filesDir, CACHE_DIR)
|
||||
val old = File(context.cacheDir, CACHE_DIR)
|
||||
if (old.isDirectory) migrate(old, dir)
|
||||
dir.mkdirs()
|
||||
return dir
|
||||
}
|
||||
|
||||
fun writeMode(dir: File, mode: String) {
|
||||
val file = File(dir, MODE_FILE)
|
||||
if (runCatching { file.readText().trim() }.getOrNull() == mode) return
|
||||
val tmp = File(dir, "$MODE_FILE.tmp")
|
||||
runCatching {
|
||||
tmp.writeText(mode + "\n")
|
||||
if (!tmp.renameTo(file)) error("rename failed")
|
||||
Log.i(TAG, "bridge mode: $mode")
|
||||
}.onFailure { Log.w(TAG, "could not write $file: $it"); tmp.delete() }
|
||||
}
|
||||
|
||||
private fun migrate(old: File, dir: File) {
|
||||
val moved = if (!dir.exists()) old.renameTo(dir) else false
|
||||
if (!moved) {
|
||||
dir.mkdirs()
|
||||
old.listFiles()?.forEach { f ->
|
||||
val to = File(dir, f.name)
|
||||
if (to.exists()) return@forEach
|
||||
if (!f.renameTo(to)) runCatching { f.copyRecursively(to, overwrite = false) }
|
||||
}
|
||||
old.deleteRecursively()
|
||||
}
|
||||
Log.i(TAG, "bridge cache moved from $old to $dir")
|
||||
}
|
||||
|
||||
const val BINARY = "libvkbridge_server.so"
|
||||
const val GUEST_ICD = "/usr/local/share/vkbridge/droidbridge_icd.json"
|
||||
const val GUEST_LIB = "/usr/local/lib/vkbridge/libvulkan_droidbridge.so"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.ApplicationInfo
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
|
||||
object VkBridgeNative {
|
||||
private const val TAG = "VkBridge"
|
||||
|
||||
@Volatile private var loaded: Boolean? = null
|
||||
|
||||
private fun load(context: Context): Boolean {
|
||||
loaded?.let { return it }
|
||||
val ok = try {
|
||||
val dev = File(context.filesDir, "vkbridge/dev/libvkbridge_jni.so")
|
||||
val debuggable = context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
|
||||
if (debuggable && dev.isFile) {
|
||||
Log.w(TAG, "in-app server from the development override $dev")
|
||||
System.load(dev.absolutePath)
|
||||
} else {
|
||||
System.loadLibrary("vkbridge_jni")
|
||||
}
|
||||
true
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "in-app server unavailable: $e")
|
||||
false
|
||||
}
|
||||
loaded = ok
|
||||
return ok
|
||||
}
|
||||
|
||||
@Volatile var serving = false
|
||||
private set
|
||||
|
||||
fun start(context: Context, socket: File, log: File, cacheDir: File): Boolean {
|
||||
if (!load(context)) return false
|
||||
val ok = try {
|
||||
nativeStart(socket.absolutePath, log.absolutePath, cacheDir.absolutePath) == 1
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "in-app server failed to start: $e")
|
||||
false
|
||||
}
|
||||
if (ok) serving = true
|
||||
return ok
|
||||
}
|
||||
|
||||
@JvmStatic private external fun nativeStart(socket: String, log: String, cacheDir: String): Int
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import java.io.FileInputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.channels.FileChannel
|
||||
|
||||
/** Hand-tracking models and the OpenCV/MediaPipe native libraries, downloaded on first use. */
|
||||
internal object TrackingPack {
|
||||
const val HAND = "hand_landmarker.task"
|
||||
const val HAND_LITE = "hand_landmarker_lite.task"
|
||||
@@ -32,10 +31,6 @@ internal object TrackingPack {
|
||||
fun model(context: Context, name: String): ByteBuffer =
|
||||
FileInputStream(file(context, name)).use { it.channel.map(FileChannel.MapMode.READ_ONLY, 0, it.channel.size()) }
|
||||
|
||||
/**
|
||||
* Loads OpenCV and MediaPipe from the pack. MediaPipe's own System.loadLibrary then resolves to the
|
||||
* already-loaded library by soname, so this must run before any MediaPipe task class initializes.
|
||||
*/
|
||||
fun loadNative(context: Context): Boolean {
|
||||
if (nativeLoaded) return true
|
||||
synchronized(lock) {
|
||||
@@ -50,7 +45,6 @@ internal object TrackingPack {
|
||||
}
|
||||
}
|
||||
|
||||
/** Blocks the calling worker thread until the pack is usable, starting the download if needed. */
|
||||
fun awaitNative(context: Context, running: () -> Boolean, onState: (AddonPack.State) -> Unit): Boolean =
|
||||
pack.await(context, running, onState) && loadNative(context)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
import android.os.SystemClock
|
||||
|
||||
internal object BottomHudPresence {
|
||||
private const val STALE_MS = 2_500L
|
||||
|
||||
@Volatile private var seenAt = 0L
|
||||
|
||||
fun beat() {
|
||||
seenAt = SystemClock.elapsedRealtime()
|
||||
}
|
||||
|
||||
val showing: Boolean get() = seenAt != 0L && SystemClock.elapsedRealtime() - seenAt < STALE_MS
|
||||
}
|
||||
+5
-11
@@ -3,14 +3,9 @@ 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.
|
||||
*/
|
||||
internal object DroidDeckHudConfig {
|
||||
val DEFAULTS: Map<String, String> = linkedMapOf(
|
||||
"hudSize" to "minimal", "hudLocked" to "1", "hudScale" to "100", "hudOpacity" to "80", "hudColor" to "mid",
|
||||
"hudSize" to "minimal", "hudLocked" to "1", "hudSnap" to "1", "hudScale" to "100", "hudDock" to "none", "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",
|
||||
@@ -20,12 +15,11 @@ internal object FusionHudConfig {
|
||||
"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)
|
||||
val stored = SessionPrefs.droidDeckHudConfig(context)
|
||||
if (stored == null) {
|
||||
values["showFPS"] = flag(SessionPrefs.hudShowFps(context))
|
||||
values["showFPSGraph"] = flag(SessionPrefs.hudShowGraph(context))
|
||||
@@ -43,12 +37,12 @@ internal object FusionHudConfig {
|
||||
if (key !in DEFAULTS) return values
|
||||
values[key] = value
|
||||
TWINS[key]?.let { values[it] = value }
|
||||
SessionPrefs.setFusionHudConfig(context, encode(values))
|
||||
SessionPrefs.setDroidDeckHudConfig(context, encode(values))
|
||||
return values
|
||||
}
|
||||
|
||||
fun reset(context: Context): Map<String, String> {
|
||||
SessionPrefs.setFusionHudConfig(context, encode(DEFAULTS))
|
||||
SessionPrefs.setDroidDeckHudConfig(context, encode(DEFAULTS))
|
||||
return DEFAULTS
|
||||
}
|
||||
|
||||
@@ -0,0 +1,517 @@
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.animation.ValueAnimator
|
||||
import android.view.Choreographer
|
||||
import android.view.View
|
||||
import android.view.animation.PathInterpolator
|
||||
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.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.ui.Motion
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class DroidDeckHudHost(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: DroidDeckHudView? = 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 anchorX = Float.NaN
|
||||
private var snaps = true
|
||||
private var snapping = false
|
||||
private var previewFade: ValueAnimator? = null
|
||||
private var flingX = 0f
|
||||
private var engine = ""
|
||||
private var gpuName = ""
|
||||
private var protonPid = 0
|
||||
private var proton = ""
|
||||
@Volatile private var lastWindow: String? = null
|
||||
|
||||
var onPresentingWindowChanged: (() -> Unit)? = null
|
||||
|
||||
val liveFps: Float? get() = if (polling) feed.stats.fps else null
|
||||
|
||||
var onConfigChanged: (() -> Unit)? = null
|
||||
|
||||
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@DroidDeckHudHost.gpuName = cleanGpuName(gpuName) }
|
||||
if (window != null && window != lastWindow) {
|
||||
lastWindow = window
|
||||
handler.post {
|
||||
onPresentingWindowChanged?.invoke()
|
||||
applyShown()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
|
||||
fun attach(root: FrameLayout, index: Int) {
|
||||
if (view != null) return
|
||||
val hud = DroidDeckHudView(root.context)
|
||||
hud.setFrameStats(feed.stats)
|
||||
hud.setMangoReadings(readings)
|
||||
hud.setGpuModel(cleanGpuName(GpuInfo.detect().displayName(context)))
|
||||
hud.onRefresh = Runnable { refreshLabels(hud) }
|
||||
hud.setOnDraggedListener { rawX, rawY ->
|
||||
anchorX = Float.NaN; snapping = false
|
||||
previewFade?.cancel(); previewFade = null
|
||||
stopMotion(hud)
|
||||
shrinkPastEdge(hud, rawX, rawY)
|
||||
}
|
||||
hud.setOnFlungListener { vx, _ -> flingX = vx }
|
||||
hud.setOnTabDraggedListener { x, y -> dragTab(hud, x, y) }
|
||||
hud.setOnTabDroppedListener { dropTab(hud) }
|
||||
hud.setOnTabDragCancelledListener { snapping = false; keepOnScreen(hud) }
|
||||
hud.setOnMovedListener { x, y ->
|
||||
wantX = x; wantY = y
|
||||
val vx = flingX
|
||||
flingX = 0f
|
||||
dockEdgeFor(hud)?.let { edge -> setDock(hud, edge); return@setOnMovedListener }
|
||||
stopMotion(hud)
|
||||
fadeDockPreview(hud)
|
||||
if (snaps && !hud.isStrip) { snapToAnchor(hud, vx); return@setOnMovedListener }
|
||||
val fromX = hud.x; val fromY = hud.y
|
||||
keepOnScreen(hud)
|
||||
wantX = hud.x; wantY = hud.y
|
||||
SessionPrefs.setDroidDeckHudPosition(context, hud.x, hud.y)
|
||||
glideFrom(hud, fromX, fromY)
|
||||
}
|
||||
hud.setOnSizeCycledListener { size -> DroidDeckHudConfig.set(context, "hudSize", size); onConfigChanged?.invoke() }
|
||||
hud.setOnDockChangedListener { token -> setDock(hud, DroidDeckHudDock.from(token)) }
|
||||
hud.setOnScaledListener { percent ->
|
||||
DroidDeckHudConfig.set(context, "hudScale", percent.toString())
|
||||
onConfigChanged?.invoke()
|
||||
}
|
||||
hud.setOnLockChangedListener { locked ->
|
||||
DroidDeckHudConfig.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.droidDeckHudPosition(context)?.let { (x, y) -> wantX = x; wantY = y; hud.post { keepOnScreen(hud) } }
|
||||
view = hud
|
||||
parent = root
|
||||
applyConfig()
|
||||
}
|
||||
|
||||
fun applyConfig() {
|
||||
val config = DroidDeckHudConfig.load(context)
|
||||
snaps = config["hudSnap"] != "0"
|
||||
if (!snaps) anchorX = Float.NaN
|
||||
view?.applyConfig(DroidDeckHudConfig.encode(config))
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
fun setHidden(hide: Boolean) {
|
||||
hidden = hide
|
||||
applyShown()
|
||||
}
|
||||
|
||||
fun setBackgrounded(stopped: Boolean) {
|
||||
backgrounded = stopped
|
||||
applyShown()
|
||||
}
|
||||
|
||||
private fun applyShown() {
|
||||
if (!running) return
|
||||
val show = !hidden && !backgrounded
|
||||
val visible = show && SessionState.mode != SessionService.MODE_DESKTOP
|
||||
view?.visibility = if (visible) View.VISIBLE else View.GONE
|
||||
showing = visible
|
||||
if (show != polling) {
|
||||
polling = show
|
||||
if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
|
||||
else Choreographer.getInstance().removeFrameCallback(frameCallback)
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
val metrics = HudMetrics(context)
|
||||
metrics.setMangoReadings(MangoReadings(File(context.filesDir, "session"), LinuxRuntime.rootDir(context)))
|
||||
metrics.snapshot()
|
||||
Thread.sleep(500)
|
||||
val mango = metrics.snapshot()
|
||||
fun shown(value: Any?, unit: String) = if (value == null) "none" else "$value$unit"
|
||||
val readers = com.droiddeck.launcher.session.GpuStatsComponent.readerStatus()
|
||||
file.writeText(metrics.also { it.setMangoReadings(null) }.buildDiagnosticsReport(context) + "\n== As the HUD shows them (MangoHud's sources) ==\n" +
|
||||
"CPU ${shown(mango.cpuPercent, "%")} ${shown(mango.cpuTempC, "°C")}, GPU ${shown(mango.gpuPercent, "%")} " +
|
||||
"${shown(mango.gpuClockMhz, "MHz")} ${shown(mango.gpuTempC, "°C")}, " +
|
||||
"RAM ${mango.ramUsedText()}/${mango.ramTotalText()}, VRAM ${mango.vramText()}, battery ${mango.battery.percent}% " +
|
||||
"${mango.battery.watts}W charging=${mango.battery.charging}\n" +
|
||||
"GPU feeds: ${com.droiddeck.launcher.session.GpuStatsComponent.sources.ifEmpty { "none (no session, or kgsl absent)" }}\n" +
|
||||
(if (readers.isNotEmpty()) "GPU readers without root: $readers\n" else "") +
|
||||
"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 sessionResolution(): String {
|
||||
val (width, height) = SessionState.outputSize
|
||||
return "${width}x${height}"
|
||||
}
|
||||
|
||||
private fun refreshLabels(hud: DroidDeckHudView) {
|
||||
if (feed.engine.isNotBlank() && !feed.steamFocused) engine = feed.engine
|
||||
hud.setEngineLabel(engine)
|
||||
if (gpuName.isNotBlank()) hud.setGpuModel(gpuName)
|
||||
val feedResolution = 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 ""
|
||||
hud.setResolution(feedResolution.ifBlank { sessionResolution() })
|
||||
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
|
||||
}
|
||||
|
||||
private fun dockEdgeFor(v: View): DroidDeckHudDock? {
|
||||
val over = overhang(v) ?: return null
|
||||
return over.key.takeIf { over.value >= DOCK_OVERHANG }
|
||||
}
|
||||
|
||||
private fun overhang(v: View): Map.Entry<DroidDeckHudDock, Float>? {
|
||||
val p = v.parent as? View ?: return null
|
||||
if (p.width <= 0 || p.height <= 0 || v.width <= 0 || v.height <= 0) return null
|
||||
val strip = (v as? DroidDeckHudView)?.isStrip == true
|
||||
val density = v.resources.displayMetrics.density
|
||||
val w = if (strip) minOf(v.width.toFloat(), STRIP_PULL_ACROSS_DP * density) else v.width.toFloat()
|
||||
val h = if (strip) maxOf(v.height.toFloat(), STRIP_PULL_OFF_DP * density) else v.height.toFloat()
|
||||
return mapOf(
|
||||
DroidDeckHudDock.LEFT to -v.x / w,
|
||||
DroidDeckHudDock.RIGHT to (v.x + v.width - p.width) / w,
|
||||
DroidDeckHudDock.TOP to -v.y / h,
|
||||
DroidDeckHudDock.BOTTOM to (v.y + v.height - p.height) / h,
|
||||
).maxByOrNull { it.value }
|
||||
}
|
||||
|
||||
private fun dragTab(hud: DroidDeckHudView, x: Float, y: Float) {
|
||||
val p = hud.parent as? View ?: return
|
||||
stopMotion(hud)
|
||||
snapping = false
|
||||
hud.x = x.coerceIn(0f, (p.width - hud.width).toFloat().coerceAtLeast(0f))
|
||||
hud.y = y.coerceIn(0f, (p.height - hud.height).toFloat().coerceAtLeast(0f))
|
||||
}
|
||||
|
||||
private fun dropTab(hud: DroidDeckHudView) {
|
||||
val p = hud.parent as? View ?: return
|
||||
val maxX = (p.width - hud.width).toFloat().coerceAtLeast(0f)
|
||||
val maxY = (p.height - hud.height).toFloat().coerceAtLeast(0f)
|
||||
val pulled = when (hud.dock) {
|
||||
DroidDeckHudDock.LEFT -> hud.x / hud.width
|
||||
DroidDeckHudDock.RIGHT -> (maxX - hud.x) / hud.width
|
||||
DroidDeckHudDock.TOP -> hud.y / hud.height
|
||||
DroidDeckHudDock.BOTTOM -> (maxY - hud.y) / hud.height
|
||||
DroidDeckHudDock.NONE -> 0f
|
||||
}
|
||||
if (pulled >= 1f) { setDock(hud, DroidDeckHudDock.NONE); return }
|
||||
wantX = hud.x; wantY = hud.y
|
||||
val (x, y) = settled(p, hud.dock, hud.width.toFloat(), hud.height.toFloat())
|
||||
wantX = x; wantY = y
|
||||
SessionPrefs.setDroidDeckHudPosition(context, x, y)
|
||||
if (Motion.scale == 0f) { hud.x = x; hud.y = y; return }
|
||||
snapping = true
|
||||
hud.animate().x(x).y(y).setDuration(Motion.ms(220).toLong()).setInterpolator(EASE)
|
||||
.withEndAction { snapping = false }.start()
|
||||
}
|
||||
|
||||
private fun stopMotion(hud: DroidDeckHudView) {
|
||||
hud.animate().setUpdateListener(null)
|
||||
hud.animate().cancel()
|
||||
}
|
||||
|
||||
private fun glideFrom(hud: DroidDeckHudView, fromX: Float, fromY: Float) {
|
||||
if (Motion.scale == 0f || (fromX == hud.x && fromY == hud.y && hud.scaleX == 1f && hud.scaleY == 1f)) {
|
||||
hud.scaleX = 1f; hud.scaleY = 1f
|
||||
return
|
||||
}
|
||||
val toX = hud.x; val toY = hud.y
|
||||
hud.x = fromX; hud.y = fromY
|
||||
snapping = true
|
||||
hud.animate().x(toX).y(toY).scaleX(1f).scaleY(1f).setDuration(Motion.ms(220).toLong()).setInterpolator(EASE)
|
||||
.withEndAction { snapping = false; keepOnScreen(hud) }.start()
|
||||
}
|
||||
|
||||
private fun fadeDockPreview(hud: DroidDeckHudView) {
|
||||
val from = hud.dockPreviewBlend
|
||||
if (from <= 0f) return
|
||||
val edge = overhang(hud)?.key ?: DroidDeckHudDock.NONE
|
||||
if (Motion.scale == 0f) { hud.setDockPreview(DroidDeckHudDock.NONE, 0f); return }
|
||||
previewFade?.cancel()
|
||||
previewFade = ValueAnimator.ofFloat(from, 0f).apply {
|
||||
duration = Motion.ms(200).toLong()
|
||||
addUpdateListener { hud.setDockPreview(edge, it.animatedValue as Float) }
|
||||
start()
|
||||
}
|
||||
}
|
||||
|
||||
private fun snapToAnchor(hud: DroidDeckHudView, vx: Float) {
|
||||
val p = hud.parent as? View ?: return
|
||||
val maxX = (p.width - hud.width).toFloat().coerceAtLeast(0f)
|
||||
val maxY = (p.height - hud.height).toFloat().coerceAtLeast(0f)
|
||||
anchorX = if (hud.x + vx * FLING_REACH_S < maxX / 2f) 0f else 1f
|
||||
wantX = anchorX * maxX
|
||||
wantY = hud.y.coerceIn(0f, maxY)
|
||||
SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY)
|
||||
stopMotion(hud)
|
||||
if (Motion.scale == 0f) {
|
||||
hud.scaleX = 1f; hud.scaleY = 1f
|
||||
hud.x = wantX; hud.y = wantY
|
||||
return
|
||||
}
|
||||
snapping = true
|
||||
hud.animate().x(wantX).y(wantY).scaleX(1f).scaleY(1f).setDuration(Motion.ms(260).toLong()).setInterpolator(EASE)
|
||||
.withEndAction { snapping = false; keepOnScreen(hud) }.start()
|
||||
}
|
||||
|
||||
private fun shrinkPastEdge(hud: DroidDeckHudView, rawX: Float, rawY: Float) {
|
||||
if (hud.dock != DroidDeckHudDock.NONE) return
|
||||
val p = hud.parent as? View ?: return
|
||||
val edge = overhang(hud) ?: return
|
||||
val over = edge.value
|
||||
val t = (over / DOCK_OVERHANG).coerceIn(0f, 1f)
|
||||
val fade = ((t - PREVIEW_FROM) / (1f - PREVIEW_FROM)).coerceIn(0f, 1f)
|
||||
hud.setDockPreview(edge.key, fade * fade * (3f - 2f * fade))
|
||||
val (tabW, tabH) = hud.dockTabSize()
|
||||
val e = t * t * (3f - 2f * t)
|
||||
val at = IntArray(2).also { p.getLocationOnScreen(it) }
|
||||
hud.pivotX = rawX - at[0] - hud.x
|
||||
hud.pivotY = rawY - at[1] - hud.y
|
||||
if (hud.isStrip) {
|
||||
hud.scaleX = 1f + (tabW / hud.width - 1f) * e
|
||||
hud.scaleY = 1f
|
||||
return
|
||||
}
|
||||
val tabScale = maxOf(tabW / hud.width, tabH / hud.height).coerceAtMost(1f)
|
||||
val s = 1f + (tabScale - 1f) * e
|
||||
hud.scaleX = s; hud.scaleY = s
|
||||
}
|
||||
|
||||
private fun setDock(hud: DroidDeckHudView, edge: DroidDeckHudDock) {
|
||||
if (edge == hud.dock) return
|
||||
animateDock(hud, edge) { commitDock(hud, edge) }
|
||||
}
|
||||
|
||||
private fun commitDock(hud: DroidDeckHudView, edge: DroidDeckHudDock) {
|
||||
val tabX = hud.x; val tabY = hud.y
|
||||
if (edge != DroidDeckHudDock.NONE) {
|
||||
val p = hud.parent as? View
|
||||
if (p != null) {
|
||||
wantX = wantX.coerceIn(0f, p.width.toFloat())
|
||||
wantY = wantY.coerceIn(0f, p.height.toFloat())
|
||||
}
|
||||
SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY)
|
||||
}
|
||||
DroidDeckHudConfig.set(context, "hudDock", edge.token)
|
||||
applyConfig()
|
||||
if (edge == DroidDeckHudDock.NONE) settleOutOfTab(hud, tabX, tabY)
|
||||
hud.post { keepOnScreen(hud) }
|
||||
onConfigChanged?.invoke()
|
||||
}
|
||||
|
||||
private fun settleOutOfTab(hud: DroidDeckHudView, tabX: Float, tabY: Float) {
|
||||
val p = hud.parent as? View
|
||||
val maxX = if (p == null) Float.MAX_VALUE else (p.width - hud.contentWidth).coerceAtLeast(0f)
|
||||
val maxY = if (p == null) Float.MAX_VALUE else (p.height - hud.contentHeight).coerceAtLeast(0f)
|
||||
wantX = tabX.coerceIn(0f, maxX); wantY = tabY.coerceIn(0f, maxY)
|
||||
anchorX = if (snaps && !hud.isStrip && p != null) (if (wantX < maxX / 2f) 0f else 1f) else Float.NaN
|
||||
if (!anchorX.isNaN()) wantX = anchorX * maxX
|
||||
SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY)
|
||||
}
|
||||
|
||||
private fun animateDock(hud: DroidDeckHudView, edge: DroidDeckHudDock, commit: () -> Unit) {
|
||||
stopMotion(hud)
|
||||
previewFade?.cancel(); previewFade = null
|
||||
snapping = false
|
||||
hud.alpha = 1f
|
||||
val p = hud.parent as? View
|
||||
if (Motion.scale == 0f || p == null || !hud.isLaidOut || hud.width <= 0) {
|
||||
hud.scaleX = 1f; hud.scaleY = 1f
|
||||
hud.setDockPreview(DroidDeckHudDock.NONE, 0f)
|
||||
commit(); return
|
||||
}
|
||||
if (edge != DroidDeckHudDock.NONE) {
|
||||
val left = hud.x + hud.pivotX * (1f - hud.scaleX); val top = hud.y + hud.pivotY * (1f - hud.scaleY)
|
||||
val shownW = hud.width * hud.scaleX; val shownH = hud.height * hud.scaleY
|
||||
hud.pivotX = 0f; hud.pivotY = 0f
|
||||
hud.x = left; hud.y = top
|
||||
val (tabW, tabH) = hud.dockTabSize()
|
||||
wantX = left + (shownW - tabW) / 2f
|
||||
wantY = top + (shownH - tabH) / 2f
|
||||
val (tabX, tabY) = settled(p, edge, tabW, tabH)
|
||||
val sx = tabW / hud.width; val sy = tabH / hud.height
|
||||
val from = hud.dockPreviewBlend
|
||||
hud.animate().x(tabX).y(tabY).scaleX(sx).scaleY(sy).setDuration(Motion.ms(220).toLong()).setInterpolator(EASE)
|
||||
.setUpdateListener { hud.setDockPreview(edge, from + (1f - from) * it.animatedFraction) }
|
||||
.withEndAction {
|
||||
hud.animate().setUpdateListener(null)
|
||||
commit()
|
||||
hud.setDockPreview(DroidDeckHudDock.NONE, 0f)
|
||||
hud.scaleX = 1f; hud.scaleY = 1f
|
||||
hud.x = tabX; hud.y = tabY
|
||||
}.start()
|
||||
} else {
|
||||
hud.scaleX = 1f; hud.scaleY = 1f
|
||||
val was = hud.dock
|
||||
val tabX = hud.x; val tabY = hud.y
|
||||
val tabW = hud.width.toFloat(); val tabH = hud.height.toFloat()
|
||||
commit()
|
||||
val w = hud.contentWidth; val h = hud.contentHeight
|
||||
val (x, y) = settled(p, DroidDeckHudDock.NONE, w, h)
|
||||
hud.x = x; hud.y = y
|
||||
val sx = tabW / w; val sy = tabH / h
|
||||
hud.pivotX = pivotFor(x, tabX, sx) - x
|
||||
hud.pivotY = pivotFor(y, tabY, sy) - y
|
||||
hud.scaleX = sx; hud.scaleY = sy
|
||||
hud.setDockPreview(was, 1f)
|
||||
hud.animate().scaleX(1f).scaleY(1f).setDuration(Motion.ms(360).toLong()).setInterpolator(EASE)
|
||||
.setUpdateListener {
|
||||
val f = (1f - it.animatedFraction / EXPAND_FADE).coerceIn(0f, 1f)
|
||||
hud.setDockPreview(was, f * f * (3f - 2f * f))
|
||||
}
|
||||
.withEndAction { hud.animate().setUpdateListener(null); hud.setDockPreview(DroidDeckHudDock.NONE, 0f) }
|
||||
.start()
|
||||
}
|
||||
}
|
||||
|
||||
private fun pivotFor(from: Float, to: Float, scale: Float): Float =
|
||||
if (scale > 0.999f) from else (to - from * scale) / (1f - scale)
|
||||
|
||||
private fun settled(p: View, dock: DroidDeckHudDock, w: Float, h: Float): Pair<Float, Float> {
|
||||
val maxX = (p.width - w).coerceAtLeast(0f); val maxY = (p.height - h).coerceAtLeast(0f)
|
||||
var x = wantX.coerceIn(0f, maxX); var y = wantY.coerceIn(0f, maxY)
|
||||
when (dock) {
|
||||
DroidDeckHudDock.LEFT -> x = 0f
|
||||
DroidDeckHudDock.RIGHT -> x = maxX
|
||||
DroidDeckHudDock.TOP -> y = 0f
|
||||
DroidDeckHudDock.BOTTOM -> y = maxY
|
||||
DroidDeckHudDock.NONE -> {}
|
||||
}
|
||||
return Pair(x, y)
|
||||
}
|
||||
|
||||
private fun keepOnScreen(v: View) {
|
||||
if (snapping) return
|
||||
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 anchored = (v as? DroidDeckHudView)?.let { it.dock == DroidDeckHudDock.NONE && !it.isStrip } == true
|
||||
if (snaps && anchored && anchorX.isNaN()) {
|
||||
anchorX = if (wantX.coerceIn(0f, maxX) < maxX / 2f) 0f else 1f
|
||||
}
|
||||
if (snaps && anchored && !anchorX.isNaN()) wantX = anchorX * maxX
|
||||
var x = wantX.coerceIn(0f, maxX)
|
||||
var y = wantY.coerceIn(0f, maxY)
|
||||
if ((v as? DroidDeckHudView)?.isStrip == true) y = if (y + v.height / 2f < p.height / 2f) 0f else maxY
|
||||
when (v.let { it as? DroidDeckHudView }?.dock) {
|
||||
DroidDeckHudDock.LEFT -> x = 0f
|
||||
DroidDeckHudDock.RIGHT -> x = maxX
|
||||
DroidDeckHudDock.TOP -> y = 0f
|
||||
DroidDeckHudDock.BOTTOM -> y = maxY
|
||||
else -> {}
|
||||
}
|
||||
if (v.x != x) v.x = x
|
||||
if (v.y != y) v.y = y
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val DOCK_OVERHANG = 0.4f
|
||||
private const val FLING_REACH_S = 0.18f
|
||||
private const val PREVIEW_FROM = 0.55f
|
||||
private const val STRIP_PULL_ACROSS_DP = 600f
|
||||
private const val STRIP_PULL_OFF_DP = 150f
|
||||
private const val EXPAND_FADE = 0.5f
|
||||
private val EASE = PathInterpolator(0.2f, 0.8f, 0.2f, 1f)
|
||||
|
||||
@Volatile @JvmStatic var showing = false
|
||||
private set
|
||||
|
||||
internal fun cleanGpuName(name: String): String = name.replace("(TM)", "").replace(Regex("\\s+"), " ").trim()
|
||||
|
||||
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,69 @@
|
||||
/*
|
||||
* 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) and modified for DroidDeck.
|
||||
*/
|
||||
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||
FULL("full", "Full"),
|
||||
TILES("tiles", "Tiles"),
|
||||
PILL("pill", "Pill"),
|
||||
MINIMAL("minimal", "Minimal"),
|
||||
MEGA("mega", "Mega"),
|
||||
STRIP("strip", "Strip");
|
||||
|
||||
fun next(): DroidDeckHudSize {
|
||||
val all = values()
|
||||
return all[(ordinal + 1) % all.size]
|
||||
}
|
||||
|
||||
fun supportedChips(): Set<String> = when (this) {
|
||||
MINIMAL -> MINIMAL_CHIPS
|
||||
PILL -> PILL_CHIPS
|
||||
FULL, TILES, STRIP -> STANDARD_CHIPS
|
||||
MEGA -> MEGA_CHIPS
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun from(token: String?): DroidDeckHudSize =
|
||||
values().firstOrNull { it.token.equals(token, ignoreCase = true) } ?: FULL
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
enum class DroidDeckHudDock(val token: String) {
|
||||
NONE("none"), LEFT("left"), RIGHT("right"), TOP("top"), BOTTOM("bottom");
|
||||
|
||||
companion object {
|
||||
fun from(token: String?): DroidDeckHudDock = values().firstOrNull { it.token == token } ?: NONE
|
||||
}
|
||||
}
|
||||
|
||||
object DroidDeckHudHdr {
|
||||
const val NONE = 0
|
||||
const val ON = 1
|
||||
const val NO_HEADROOM = 2
|
||||
const val OFF = 3
|
||||
const val READY = 4
|
||||
const val TONEMAPPED = 5
|
||||
const val NOT_ON_THIS_SCREEN = 6
|
||||
}
|
||||
+375
-258
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,6 @@ 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
|
||||
@@ -36,7 +35,6 @@ internal object DroidDeckMark {
|
||||
|
||||
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
|
||||
|
||||
|
||||
@@ -1,236 +0,0 @@
|
||||
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() }
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
/*
|
||||
* 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.
|
||||
}
|
||||
@@ -3,13 +3,6 @@ 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
|
||||
@@ -26,14 +19,16 @@ internal class FrameStats {
|
||||
private var sessionStartNs = 0L
|
||||
private var sessionFrames = 0L
|
||||
|
||||
private val slowTimes = LongArray(SLOW_FRAMES)
|
||||
private var slowHead = 0
|
||||
private var slowSize = 0
|
||||
|
||||
@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
|
||||
|
||||
@@ -60,6 +55,11 @@ internal class FrameStats {
|
||||
if (lowsSize < LOWS_FRAMES) lowsSize++
|
||||
if (sessionStartNs == 0L) sessionStartNs = timeNs - frametimeNs
|
||||
sessionFrames++
|
||||
if (frametimeNs > SLOW_NS) {
|
||||
slowTimes[slowHead] = timeNs
|
||||
slowHead = (slowHead + 1) % SLOW_FRAMES
|
||||
if (slowSize < SLOW_FRAMES) slowSize++
|
||||
}
|
||||
}
|
||||
count++
|
||||
}
|
||||
@@ -77,14 +77,14 @@ internal class FrameStats {
|
||||
cachedLowsNs = 0L
|
||||
sessionStartNs = 0L
|
||||
sessionFrames = 0L
|
||||
slowHead = 0
|
||||
slowSize = 0
|
||||
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]
|
||||
@@ -96,7 +96,6 @@ internal class FrameStats {
|
||||
@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
|
||||
@@ -106,13 +105,22 @@ internal class FrameStats {
|
||||
@Synchronized
|
||||
fun sessionSeconds(nowNs: Long): Float = if (sessionStartNs == 0L) 0f else (nowNs - sessionStartNs) / 1e9f
|
||||
|
||||
@Synchronized
|
||||
fun slowFrames(nowNs: Long, windowNs: Long): Int {
|
||||
var n = 0
|
||||
for (i in 0 until slowSize) {
|
||||
if (nowNs - slowTimes[(slowHead - 1 - i + SLOW_FRAMES) % SLOW_FRAMES] > windowNs) break
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -141,15 +149,12 @@ internal class FrameStats {
|
||||
const val FPS_PERIOD_NS = 500_000_000L
|
||||
const val LOWS_FRAMES = 8192
|
||||
private const val PAUSE_NS = 1_000_000_000L
|
||||
const val SLOW_NS = 33_333_334L
|
||||
private const val SLOW_FRAMES = 2048
|
||||
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
|
||||
@@ -160,7 +165,7 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
||||
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
|
||||
@Volatile private var compositorFrames = 0L
|
||||
private var seenCompositorFrames = 0L
|
||||
|
||||
@Volatile var engine = ""
|
||||
@@ -176,7 +181,8 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
||||
@Volatile var refreshMilliHz = 0
|
||||
private set
|
||||
|
||||
/** Main thread, once per display frame. True when new frames arrived. */
|
||||
val live: Boolean get() = fromGamescope
|
||||
|
||||
fun poll(nowNs: Long): Boolean {
|
||||
val compositorAdded = compositorFrames != seenCompositorFrames
|
||||
seenCompositorFrames = compositorFrames
|
||||
@@ -185,7 +191,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
||||
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)
|
||||
@@ -199,7 +204,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
||||
} 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
|
||||
@@ -208,7 +212,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
||||
return n > 0 || compositorAdded
|
||||
}
|
||||
|
||||
/** Compositor thread: one frame shown on the panel. */
|
||||
fun onCompositorFrame(nowNs: Long) {
|
||||
if (fromGamescope) {
|
||||
lastCompositorNs = 0L
|
||||
@@ -247,8 +250,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
|
||||
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"
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
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
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
* 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.
|
||||
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD) and modified for DroidDeck.
|
||||
*/
|
||||
|
||||
package com.droiddeck.launcher.hud;
|
||||
@@ -22,45 +22,24 @@ import android.graphics.RectF;
|
||||
import android.os.SystemClock;
|
||||
import android.view.GestureDetector;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.ScaleGestureDetector;
|
||||
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. */
|
||||
default void onDragged(float rawX, float rawY) {}
|
||||
default void onFlung(float velocityX, float velocityY) {}
|
||||
void onLockChanged(boolean locked);
|
||||
default void onPinch(float factor) {}
|
||||
default void onPinchEnd() {}
|
||||
}
|
||||
|
||||
// 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;
|
||||
@@ -70,14 +49,14 @@ public class HudLockController {
|
||||
private final View view;
|
||||
private final Callbacks cb;
|
||||
private final GestureDetector detector;
|
||||
private final ScaleGestureDetector scaleDetector;
|
||||
|
||||
private boolean locked = false;
|
||||
|
||||
// Drag state
|
||||
private float downRawX, downRawY, startX, startY;
|
||||
private boolean dragging = false;
|
||||
private boolean pinched = false;
|
||||
|
||||
// Fade state
|
||||
private long fadeStart = 0;
|
||||
private long holdMs = HOLD_TOGGLE_MS;
|
||||
private boolean fadeShowLocked = false;
|
||||
@@ -90,21 +69,22 @@ public class HudLockController {
|
||||
this.cb = cb;
|
||||
this.detector = new GestureDetector(context, new Listener());
|
||||
this.detector.setIsLongpressEnabled(true);
|
||||
this.scaleDetector = new ScaleGestureDetector(context, new PinchListener());
|
||||
this.scaleDetector.setQuickScaleEnabled(false);
|
||||
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) {
|
||||
scaleDetector.onTouchEvent(event);
|
||||
detector.onTouchEvent(event);
|
||||
int action = event.getActionMasked();
|
||||
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
|
||||
@@ -122,12 +102,12 @@ public class HudLockController {
|
||||
startX = view.getX();
|
||||
startY = view.getY();
|
||||
dragging = false;
|
||||
pinched = 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);
|
||||
@@ -135,29 +115,58 @@ public class HudLockController {
|
||||
|
||||
@Override
|
||||
public boolean onSingleTapUp(MotionEvent e) {
|
||||
if (pinched) return true;
|
||||
if (locked) {
|
||||
flash(true, HOLD_REFLASH_MS); // intentionally locked — remind the user
|
||||
flash(true, HOLD_REFLASH_MS);
|
||||
} else {
|
||||
cb.onTap();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
|
||||
if (dragging && !locked && !pinched) cb.onFlung(velocityX, velocityY);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
|
||||
if (pinched) return true;
|
||||
if (locked) {
|
||||
if (!dragging) flash(true, HOLD_REFLASH_MS);
|
||||
dragging = true; // mark so the blocked drag doesn't fall through to a tap
|
||||
dragging = true;
|
||||
return true;
|
||||
}
|
||||
view.setX(startX + (e2.getRawX() - downRawX));
|
||||
view.setY(startY + (e2.getRawY() - downRawY));
|
||||
dragging = true;
|
||||
cb.onDragged(e2.getRawX(), e2.getRawY());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Fade badge -------------------------------------------------------
|
||||
private final class PinchListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
|
||||
@Override
|
||||
public boolean onScaleBegin(ScaleGestureDetector d) {
|
||||
if (locked) return false;
|
||||
pinched = true;
|
||||
dragging = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onScale(ScaleGestureDetector d) {
|
||||
cb.onPinch(d.getScaleFactor());
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScaleEnd(ScaleGestureDetector d) {
|
||||
cb.onPinchEnd();
|
||||
}
|
||||
}
|
||||
|
||||
private void flash(boolean showLocked, long hold) {
|
||||
fadeShowLocked = showLocked;
|
||||
holdMs = hold;
|
||||
@@ -190,14 +199,6 @@ public class HudLockController {
|
||||
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;
|
||||
@@ -216,14 +217,12 @@ public class HudLockController {
|
||||
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) {
|
||||
@@ -231,7 +230,6 @@ public class HudLockController {
|
||||
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) {
|
||||
@@ -243,19 +241,16 @@ public class HudLockController {
|
||||
|
||||
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
|
||||
canvas.drawLine(cx + r, shackleTop + r, cx + r, bodyTop, iconStroke);
|
||||
Path p = new Path();
|
||||
p.addArc(arc, 180f, 180f);
|
||||
p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop); // full-length left leg
|
||||
p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop);
|
||||
canvas.save();
|
||||
canvas.rotate(-42f, cx + r, shackleTop + r);
|
||||
canvas.drawPath(p, iconStroke);
|
||||
|
||||
Loaded 100 of 819 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user