Merge main

This commit is contained in:
Daniel Noam committed 2026-11-03 19:32:54 +02:00
commit 627aea0e8f
124 files changed
+4060 -298

No files matched your search

@@ -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
@@ -163,6 +163,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)
@@ -496,19 +500,39 @@ class FrontEndActivity : ComponentActivity() {
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) Thread({
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()
if (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()
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)
@@ -1056,6 +1080,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,
@@ -1204,6 +1229,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)
@@ -1681,6 +1715,7 @@ class FrontEndActivity : ComponentActivity() {
override fun onResume() {
super.onResume()
if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
compatLaunchVisible = true
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, false)
@@ -2141,6 +2176,8 @@ class FrontEndActivity : ComponentActivity() {
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,
@@ -2208,6 +2245,8 @@ class FrontEndActivity : ComponentActivity() {
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)
@@ -2217,6 +2256,7 @@ class FrontEndActivity : ComponentActivity() {
SteamLibraries.remove(this, id)
steamLibraries = SteamLibraries.list(this)
refresh()
refreshFoundSteamLibraries()
},
onStorageDiagnostics = { on ->
SessionPrefs.setStorageDiagnosticsEnabled(this, on)
@@ -2453,6 +2493,7 @@ class FrontEndActivity : ComponentActivity() {
refreshWifiDiscovery()
gameStorage = SessionPrefs.gameStorage(this)
steamLibraries = SteamLibraries.list(this)
if (mode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this)
settingsMode = mode
Thread({
@@ -2483,6 +2524,7 @@ class FrontEndActivity : ComponentActivity() {
SessionPrefs.setGameStorage(this, path, label)
gameStorage = path
checkUsbLink()
if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
}
private fun checkUsbLink() {
@@ -2506,6 +2548,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)
@@ -2542,6 +2587,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)
@@ -2646,7 +2694,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)
}
@@ -2665,7 +2713,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
@@ -37,6 +37,7 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.unit.dp
@@ -294,9 +295,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun alignCursorToGuest(): Boolean {
if (pointerLocked || !CompositorHost.isStarted) return false
if (!WaylandCompositor.nativeCursorInputPos(cursorPosBuf)) return false
if (surfaceView.width <= 0 || surfaceView.height <= 0) return false
val x = cursorPosBuf[0] / InputSpace.WIDTH.toFloat() * surfaceView.width
val y = cursorPosBuf[1] / InputSpace.HEIGHT.toFloat() * surfaceView.height
if (outputView().width <= 0 || outputView().height <= 0) return false
val x = cursorPosBuf[0] / InputSpace.WIDTH.toFloat() * outputView().width
val y = cursorPosBuf[1] / InputSpace.HEIGHT.toFloat() * outputView().height
if (kotlin.math.abs(x - cursorPos.x) < 0.75f && kotlin.math.abs(y - cursorPos.y) < 0.75f) return false
cursorPos = androidx.compose.ui.geometry.Offset(x, y)
return true
@@ -421,6 +422,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var glassesSettings by mutableStateOf(Glasses.settings.value)
private var glassesScreen: GlassesScreen? = null
private var glassesOutputActive by mutableStateOf(false)
private var bottomGame: com.droiddeck.launcher.ui.BottomGameScreen? = null
private var bottomOutputActive by mutableStateOf(false)
private val topDesktopKeys = mutableSetOf<Pair<Int, Int>>()
private var bottomRecoveries = 0
private var gameOnBottom by mutableStateOf(SessionState.gameOnBottom)
private var bottomSwapAvailable by mutableStateOf(false)
private var pausedFrame by mutableStateOf<com.droiddeck.launcher.ui.PausedFrame?>(null)
private var pausedFrameWanted = false
private var pauseAnimated by mutableStateOf(false)
@@ -477,6 +484,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var secondScreenPresentation: SecondScreenPresentation? = null
private val bottomScreenListener: () -> Unit = {
if (secondScreenPresentation?.display?.displayId?.let(com.droiddeck.launcher.input.DualScreen::taken) == true) closeSecondScreen(reset = false)
updateBottomGame()
refreshSecondScreenDisplays()
}
@@ -494,6 +502,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onDisplayChanged(displayId: Int) {
notifyActivityDisplayStateChanged(displayId)
followPanelRefresh(displayId)
updateBottomGame()
refreshSecondScreenDisplays()
}
}
@@ -525,7 +534,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun followPanelRefresh(displayId: Int) {
if (!CompositorHost.isStarted) return
val output = glassesScreen?.display
val output = bottomGame?.takeIf { bottomOutputActive }?.display ?: glassesScreen?.display
?: (if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay) ?: return
if (output.displayId != displayId) return
applyOutputPacing()
@@ -585,6 +594,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionEvents.begin(this, mode, SessionPaths.label(mode, intent.getStringExtra(SessionService.EXTRA_PROGRAM)))
SessionState.secondScreenAutoOpened = false
SessionState.secondScreenProvisional = false
SessionState.gameOnBottom = false
gameOnBottom = false
}
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
@@ -844,9 +855,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
androidx.compose.runtime.DisposableEffect(Unit) {
onDispose { com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity, false) }
}
androidx.compose.runtime.LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, pipUi) { updatePointerCapture() }
androidx.compose.runtime.LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, pipUi, bottomOutputActive) { updatePointerCapture() }
androidx.compose.runtime.LaunchedEffect(bottomOutputActive) { hud.setHidden(pipUi || bottomOutputActive) }
androidx.compose.runtime.LaunchedEffect(pipUi) {
hud.setHidden(pipUi)
hud.setHidden(pipUi || bottomOutputActive)
applyOutputPacing()
if (pipUi != frameGenPip) {
frameGenPip = pipUi
@@ -882,10 +894,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
} else {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
CursorOverlay({ cursorPos }, cursorVisible && !uiPointer,
CursorOverlay({ cursorPos }, cursorVisible && !uiPointer && !bottomOutputActive,
resources.displayMetrics.density,
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
if (memoryHud.text.isNotEmpty()) HudText(memoryHud.text, hudColor, hudOpacity)
if (bottomOutputActive && !loading.visible) SwappedTopPanel()
val phonePanel = glassesOutputActive && !loading.visible && !drawerOpen && !pcKeyboardOpen
if (phonePanel) GlassesPhonePanel(glasses, steamVrStatus == SteamVr.Status.RUNNING, headTracking)
if (trackingRecovery != null && !drawerOpen && !pcKeyboardOpen && !loading.visible) {
@@ -1192,6 +1205,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
touchAuto = getString(if (usingTouchpad()) R.string.session_touch_auto_touchpad else R.string.session_touch_auto_direct),
fexPreset = fexPreset,
secondScreenMode = secondScreenMode,
gameOnBottom = bottomOutputActive,
gameSwapAvailable = bottomSwapAvailable,
onGameOnBottom = { on -> drawerOpen = false; putGameOnBottom(on) },
dashboardAvailable = bottomPages().isNotEmpty(),
desktopAvailable = com.droiddeck.launcher.session.BottomDesktop.available(),
secondScreenDisplays = secondScreenDisplays,
@@ -1928,7 +1944,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
if (problem == null) SessionEvents.record("package.ready") else failedComponent = "package"
}
if (problem == null && desktop && !SessionState.stopRequested) {
if (problem == null && desktop && !SessionState.stopRequested &&
!((runtime || resume) && com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this))) {
if (activeInstallWorker === worker) SessionState.installing = "desktop"
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "desktop.installing", mapOf("component" to "desktop"))
problem = installDesktop()
@@ -2073,7 +2090,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
val size = live ?: if (SessionState.running) previous else glassesOutputSize() ?: outputSize()
SessionState.outputSize = size
if (!SessionState.running) SessionState.refreshHz = refreshHz()
if (!SessionState.running) SessionState.refreshHz = refreshHz(holder)
val panel = panelBounds()
SessionState.upscaleRatio = maxOf(panel.width(), panel.height()).toFloat() / maxOf(size.first, size.second).coerceAtLeast(1)
Thread({
@@ -2123,7 +2140,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
CompositorHost.startOrAttach(
this, holder.surface, runtimeDir.path,
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(), outputFpsLimit(),
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), outputFpsLimit(),
)
onOutputAttached(holder)
if (SessionState.running && size != previous) {
@@ -2165,6 +2182,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun windowOutputSize(width: Int, height: Int): Pair<Int, Int>? {
if (isInPictureInPictureMode || width <= 0 || height <= 0) return null
if (bottomGame != null) return when {
SessionState.followScreen ->
com.droiddeck.launcher.session.SessionDisplay.followSize(width, height, false, SessionState.followScale)
resolutionChoice() == com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN ->
(width and 1.inv()) to (height and 1.inv())
else -> null
}
return if (SessionState.followScreen)
com.droiddeck.launcher.session.SessionDisplay.followSize(width, height, controlsBelowWanted(), SessionState.followScale)
else if (glassesScreen == null) outputSize() else null
@@ -2211,12 +2235,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun surfaceDestroyed(holder: SurfaceHolder) {
if (holder !== outputHolder()) return
cancelTouchGestures()
cancelOutputTouches()
surfaceW = 0
surfaceH = 0
glassesOutputActive = false
bottomOutputActive = false
if (CompositorHost.isStarted) WaylandCompositor.nativeSetCursorComposite(false)
CompositorHost.detach(holder.surface)
bottomGame?.takeIf { it.holder === holder }?.let { screen -> uiHandler.post { recoverBottomOutput(screen) } }
}
private fun cancelTouchGestures() {
@@ -2239,19 +2265,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun displayMode(): String = SessionPrefs.displayMode(this,
intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, intent.getStringExtra(SessionService.EXTRA_PROGRAM))
private fun outputSize(): Pair<Int, Int> {
private fun outputSize(): Pair<Int, Int> =
com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
resolutionChoice(), SessionPrefs.portrait(this) && !controlsBelowWanted())
private fun resolutionChoice(): String {
val mode = displayMode()
val panel = com.droiddeck.launcher.session.SessionDisplay.panelSize(this)
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
val choice = if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
return if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode))
com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN
else SessionPrefs.resolutionChoice(this, mode, panel)
return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panel, choice,
SessionPrefs.portrait(this) && !controlsBelowWanted())
else SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
}
private fun refreshHz(): Float {
private fun refreshHz(): Float = refreshHz(null)
private fun refreshHz(holder: SurfaceHolder?): Float {
bottomGame?.takeIf { if (holder != null) holder === it.holder else bottomOutputActive }
?.hz?.takeIf { it > 1f }?.let { return minOf(it, PerfMode.peakRefreshCap(this)) }
glassesScreen?.hz?.takeIf { it > 1f }?.let { return it }
val display = if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay
val wanted = window.attributes.preferredDisplayModeId
@@ -2600,6 +2631,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return true
}
if ((pcKeyboardOpen || achievementsOpen) && fromController) return super.dispatchKeyEvent(event)
if (!fromController && event.keyCode != KeyEvent.KEYCODE_BACK && sendToTopDesktop(event)) return true
if (joyConVr?.onKeyEvent(event) == true) return true
if (fromController && event.keyCode != KeyEvent.KEYCODE_BACK && padMouseMode() && padMouse.onKey(event)) return true
if (event.keyCode != KeyEvent.KEYCODE_BACK && padBridge?.onKeyEvent(event) == true) return true
@@ -2611,6 +2643,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return super.dispatchKeyEvent(event)
}
private fun sendToTopDesktop(event: KeyEvent): Boolean {
val key = event.deviceId to event.keyCode
val owned = if (event.action == KeyEvent.ACTION_UP) topDesktopKeys.remove(key) else topDesktopFocused()
if (!owned || !super.dispatchKeyEvent(event)) return false
if (event.action == KeyEvent.ACTION_DOWN) topDesktopKeys += key
return true
}
private fun topDesktopFocused(): Boolean {
if (!bottomOutputActive) return false
var view: View? = currentFocus
while (view != null) {
if (view is com.droiddeck.launcher.ui.BottomDesktopPanel) return true
view = view.parent as? View
}
return false
}
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
if (pipUi) return true
notePress(event)
@@ -2750,7 +2800,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun focusDrawer(): Boolean = dockedMenu()?.focusMenu() ?: sessionOverlay.requestFocus()
private fun dockDrawer(): Boolean {
if (pipUi || !started || glassesScreen != null || !::displayManager.isInitialized) return false
if (pipUi || !started || glassesScreen != null || bottomGame != null || !::displayManager.isInitialized) return false
val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return false
if (secondScreenDisplays.none { it.id == target.displayId }) return false
val shown = secondScreenPresentation?.display?.displayId
@@ -2865,7 +2915,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val rect = drawnRect() ?: return
val cx = x.coerceIn(rect.left, rect.right)
val cy = y.coerceIn(rect.top, rect.bottom)
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, surfaceView.width), InputSpace.y(cy, surfaceView.height))
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, outputView().width), InputSpace.y(cy, outputView().height))
cursorVisible = false
}
override fun onButton(button: Int, pressed: Boolean) {
@@ -2893,7 +2943,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
scrollRestY = 0f
val rect = drawnRect() ?: return
val x = rect.left + rect.width() * PAD_SCROLL_POINTER_X
WaylandCompositor.nativeSendPointer(1, InputSpace.x(x, surfaceView.width), InputSpace.y(rect.centerY(), surfaceView.height))
WaylandCompositor.nativeSendPointer(1, InputSpace.x(x, outputView().width), InputSpace.y(rect.centerY(), outputView().height))
cursorVisible = false
}
override fun onScroll(dx: Float, dy: Float) = scrollListener.onScroll(dx, dy)
@@ -2941,10 +2991,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun placeTouchpadAtGuest(rect: android.graphics.RectF) {
if (pointerLocked || !CompositorHost.isStarted || surfaceView.width <= 0 || surfaceView.height <= 0) return
if (pointerLocked || !CompositorHost.isStarted || outputView().width <= 0 || outputView().height <= 0) return
if (!WaylandCompositor.nativeCursorInputPos(cursorPosBuf)) return
val x = cursorPosBuf[0] / InputSpace.WIDTH.toFloat() * surfaceView.width
val y = cursorPosBuf[1] / InputSpace.HEIGHT.toFloat() * surfaceView.height
val x = cursorPosBuf[0] / InputSpace.WIDTH.toFloat() * outputView().width
val y = cursorPosBuf[1] / InputSpace.HEIGHT.toFloat() * outputView().height
if (rect.contains(x, y)) touchpad.place(x, y)
}
@@ -2960,7 +3010,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val rect = drawnRect() ?: return
val cx = x.coerceIn(rect.left, rect.right)
val cy = y.coerceIn(rect.top, rect.bottom)
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, surfaceView.width), InputSpace.y(cy, surfaceView.height))
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, outputView().width), InputSpace.y(cy, outputView().height))
showCursor(cx, cy)
}
@@ -3025,6 +3075,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
.filter { glassesScreen == null || it.id != glasses.displayId }
val oldIds = secondScreenDisplays.map { it.id }.toSet()
secondScreenDisplays = candidates
bottomSwapAvailable = bottomGame != null || bottomGameDisplay() != null
val newIds = candidates.map { it.id }.toSet()
if (secondScreenMode != SecondScreenMode.NONE && oldIds.isNotEmpty() && selectedSecondScreenDisplay !in newIds) {
closeSecondScreen(reset = true)
@@ -3091,7 +3142,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
closeSecondScreen(reset = false)
return
}
if (com.droiddeck.launcher.input.DualScreen.taken(target.displayId)) {
if (com.droiddeck.launcher.input.DualScreen.taken(target.displayId) || bottomGame?.display?.displayId == target.displayId) {
if (secondScreenPresentation != null) closeSecondScreen(reset = false)
secondScreenMode = mode
SessionState.secondScreenMode = mode
@@ -3133,6 +3184,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
menu = {
DroidDeckTheme { SessionMenu(docked = true) }
},
onSwap = if (com.droiddeck.launcher.input.DualScreen.builtIn(target)) ({ putGameOnBottom(true) }) else null,
dashboard = if (bottomPages().isEmpty()) null else ({
DroidDeckTheme {
BottomDashboard(
@@ -3141,6 +3193,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onPage = { com.droiddeck.launcher.ui.SessionBottomTab.pick(SessionState.sessionId, it) },
onClose = { selectSecondScreenMode(SecondScreenMode.NONE) },
onMenu = if (dockDrawer()) ({ drawerOpen = true }) else null,
onSwap = if (bottomSwapAvailable && com.droiddeck.launcher.input.DualScreen.builtIn(target)) ({ putGameOnBottom(true) }) else null,
strip = { pageId ->
com.droiddeck.launcher.ui.SessionBottomStrip(pageId) { if (::hud.isInitialized) hud.liveFps else null }
},
@@ -3157,7 +3210,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
))
private fun openSettingsBelow(intent: android.content.Intent, done: () -> Boolean) {
val presentation = secondScreenPresentation ?: return
val presentation = secondScreenPresentation
if (presentation == null) {
if (!bottomOutputActive) return
listOf(intent, android.content.Intent(android.provider.Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)).any {
runCatching { startActivity(android.content.Intent(it)) }
.onFailure { e -> Log.w(TAG, "could not open ${it.action}", e) }
.isSuccess
}
return
}
val options = android.app.ActivityOptions.makeBasic().setLaunchDisplayId(presentation.display.displayId)
val opened = listOf(intent, android.content.Intent(android.provider.Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)).any {
runCatching { startActivity(android.content.Intent(it).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK), options.toBundle()) }
@@ -3188,7 +3250,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun captureScreenshot(onDone: (Boolean) -> Unit) {
val source = if (glassesOutputActive) glassesScreen?.surfaceView else if (::surfaceView.isInitialized) surfaceView else null
val source = if (glassesOutputActive) glassesScreen?.surfaceView else if (bottomOutputActive) bottomGame?.surfaceView
else if (::surfaceView.isInitialized) surfaceView else null
val width = source?.width ?: 0
val height = source?.height ?: 0
if (source == null || width <= 0 || height <= 0 || source.holder.surface?.isValid != true) {
@@ -3252,7 +3315,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun controlsBelowWanted(): Boolean {
if (!::sessionRoot.isInitialized || glassesScreen != null || cardboard.enabled) return false
if (!::sessionRoot.isInitialized || glassesScreen != null || bottomGame != null || cardboard.enabled) return false
return SessionPrefs.controlsBelowWanted(this, SessionState.mode, sessionRoot.width, sessionRoot.height,
pipUi || isInPictureInPictureMode)
}
@@ -3298,7 +3361,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val rect = drawnRect() ?: return
val px = rect.left + nx * rect.width()
val py = rect.top + ny * rect.height()
WaylandCompositor.nativeSendPointer(1, InputSpace.x(px, surfaceView.width), InputSpace.y(py, surfaceView.height))
WaylandCompositor.nativeSendPointer(1, InputSpace.x(px, outputView().width), InputSpace.y(py, outputView().height))
showCursor(px, py)
}
@@ -3463,8 +3526,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun drawnRect(): android.graphics.RectF? {
val width = surfaceView.width.takeIf { it > 0 } ?: return null
val height = surfaceView.height.takeIf { it > 0 } ?: return null
val width = outputView().width.takeIf { it > 0 } ?: return null
val height = outputView().height.takeIf { it > 0 } ?: return null
topPictureMapped = CompositorHost.isStarted && WaylandCompositor.nativeGamePictureRect(gamePictureBounds)
if (topPictureMapped) return android.graphics.RectF(
gamePictureBounds[0], gamePictureBounds[1], gamePictureBounds[2], gamePictureBounds[3])
@@ -3560,7 +3623,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val cx = x.coerceIn(rect.left, rect.right)
val cy = y.coerceIn(rect.top, rect.bottom)
WaylandCompositor.nativeSendTouch(action, pointerId,
InputSpace.x(cx, surfaceView.width), InputSpace.y(cy, surfaceView.height))
InputSpace.x(cx, outputView().width), InputSpace.y(cy, outputView().height))
showCursor(cx, cy)
}
@@ -3624,7 +3687,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun updatePointerCapture() {
if (!::surfaceView.isInitialized) return
val view = window.decorView
val want = pointerLocked && resumed && hasWindowFocus() && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !pipUi && mouseAttached()
val want = pointerLocked && resumed && hasWindowFocus() && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !pipUi && !bottomOutputActive && mouseAttached()
if (want == view.hasPointerCapture()) return
if (want) view.requestPointerCapture() else view.releasePointerCapture()
}
@@ -3632,7 +3695,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var platformPointerShown: Boolean? = null
private fun appUiOwnsPointer(): Boolean =
drawerOpen || pcKeyboardOpen || achievementsOpen || pipUi || glassesOutputActive
drawerOpen || pcKeyboardOpen || achievementsOpen || pipUi || glassesOutputActive || bottomOutputActive
private fun applyPlatformPointer(shown: Boolean) {
if (!::sessionRoot.isInitialized || !::surfaceView.isInitialized) return
@@ -3855,7 +3918,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun capturePausedFrame(manual: Boolean = false) {
if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive) return
if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive || bottomOutputActive) return
if (SessionState.suspended && pausedFrame != null) return
if ((suspendPolicy == SessionPrefs.SUSPEND_NEVER && !manual && !SessionState.manualPause) || !::surfaceView.isInitialized) return
if (surfaceView.holder.surface?.isValid != true) return
@@ -3970,6 +4033,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (!inPip && surfaceW > 0) resizeOutputForWindow(surfaceW, surfaceH)
applyUnfoldedControls()
updateGlassesScreen()
updateBottomGame()
}
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
@@ -3999,6 +4063,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionService.setActivityVisible(this, true, sessionActivityDisplayId)
Glasses.rescan()
updateGlassesScreen()
updateBottomGame()
updateHandCamera()
}
@@ -4013,6 +4078,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
closeSecondScreen(reset = false)
startedScreens = (startedScreens - 1).coerceAtLeast(0)
updateGlassesScreen()
updateBottomGame()
if (startedScreens == 0) SessionService.setActivityVisible(this, false, sessionActivityDisplayId)
super.onStop()
}
@@ -4322,15 +4388,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
glassesScreen?.trackingRecovery?.update(trackingRecovery, glasses.sbs)
}
private fun outputHolder(): SurfaceHolder = glassesScreen?.holder ?: surfaceView.holder
private fun outputHolder(): SurfaceHolder = glassesScreen?.holder ?: bottomGame?.holder ?: surfaceView.holder
private fun outputView(): SurfaceView = bottomGame?.takeIf { bottomOutputActive }?.surfaceView ?: surfaceView
private fun onOutputAttached(holder: SurfaceHolder) {
if (holder !== outputHolder()) return
glassesOutputActive = glassesScreen?.holder === holder
if (CompositorHost.isStarted) WaylandCompositor.nativeSetCursorComposite(glassesOutputActive)
surfaceView.visibility = if (glassesOutputActive) View.INVISIBLE else View.VISIBLE
bottomOutputActive = bottomGame?.holder === holder
if (bottomOutputActive) bottomRecoveries = 0
if (CompositorHost.isStarted) WaylandCompositor.nativeSetCursorComposite(glassesOutputActive || bottomOutputActive)
surfaceView.visibility = if (glassesOutputActive || bottomOutputActive) View.INVISIBLE else View.VISIBLE
Log.i(TAG, "compositor output attached: " +
if (glassesOutputActive) "glasses display ${glassesScreen?.display?.displayId}" else "phone")
if (glassesOutputActive) "glasses display ${glassesScreen?.display?.displayId}"
else if (bottomOutputActive) "bottom screen display ${bottomGame?.display?.displayId}" else "phone")
if (pausedFrameWanted) uiHandler.postDelayed({
if (pausedFrameWanted && pausedFrame == null && resumed) capturePausedFrame()
}, PAUSED_FRAME_REDRAW_MS)
@@ -4348,6 +4419,140 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (surfaceView.holder.surface?.isValid == true) surfaceCreated(surfaceView.holder)
}
private fun bottomGameDisplay(): Display? {
if (!::displayManager.isInitialized) return null
return com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId)
?.takeIf { it.isValid && com.droiddeck.launcher.input.DualScreen.builtIn(it) }
}
private fun putGameOnBottom(on: Boolean) {
if (on && bottomGame == null && bottomGameDisplay() == null) {
android.widget.Toast.makeText(this, R.string.swap_screens_unavailable, android.widget.Toast.LENGTH_SHORT).show()
return
}
SessionState.gameOnBottom = on
gameOnBottom = on
Log.i(TAG, "game screen: " + if (on) "bottom" else "top")
updateBottomGame()
}
private fun updateBottomGame() {
if (!::surfaceView.isInitialized) return
val target = bottomGameDisplay()
val want = com.droiddeck.launcher.ui.GameScreenSwap.wanted(
requested = gameOnBottom,
activityStarted = started && !runtimeRemovalBlocked,
sessionEnded = ended,
inPip = pipUi || isInPictureInPictureMode,
glassesOutput = glassesScreen != null,
bottomScreenFree = target != null,
)
val shown = if (want) target else null
val current = bottomGame
if (current != null && current.display.displayId == shown?.displayId) return
if (current != null || shown != null) cancelOutputTouches()
if (current != null) {
restoreTopOutput(current)
runCatching { current.dismiss() }
}
if (shown != null) {
closeSecondScreen(reset = false)
val screen = com.droiddeck.launcher.ui.BottomGameScreen(this, shown, this, ::onBottomGameTouch)
bottomGame = screen
surfaceW = 0
surfaceH = 0
screen.setOnDismissListener {
if (bottomGame === screen) {
restoreTopOutput(screen)
refreshSecondScreenDisplays()
}
}
try {
screen.show()
} catch (e: Exception) {
restoreTopOutput(screen)
runCatching { screen.dismiss() }
Log.w(TAG, "could not show the game on ${shown.name}", e)
}
if (bottomGame === screen) Log.i(TAG, "requested game output on the bottom screen (display ${shown.displayId})")
}
refreshSecondScreenDisplays()
}
private fun cancelOutputTouches() {
cancelTouchGestures()
if (::directTouchHold.isInitialized) directTouchHold.cancel()
if (::twoFingerGestures.isInitialized) twoFingerGestures.cancel()
if (CompositorHost.isStarted && deliversTouches(routedTouchMode)) WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
}
private fun recoverBottomOutput(screen: com.droiddeck.launcher.ui.BottomGameScreen) {
if (bottomGame !== screen || bottomOutputActive || !started || screen.holder.surface?.isValid == true) return
Log.i(TAG, "bottom screen surface gone - game back on the top screen")
restoreTopOutput(screen)
runCatching { screen.dismiss() }
refreshSecondScreenDisplays()
if (++bottomRecoveries <= BOTTOM_RECOVERY_TRIES) uiHandler.postDelayed({ updateBottomGame() }, BOTTOM_RECOVERY_MS)
}
private fun restoreTopOutput(screen: com.droiddeck.launcher.ui.BottomGameScreen) {
if (bottomGame !== screen) return
bottomGame = null
bottomOutputActive = false
surfaceW = 0
surfaceH = 0
CompositorHost.detach(screen.holder.surface)
if (glassesScreen != null) return
surfaceView.visibility = View.VISIBLE
applyOutputPacing()
if (surfaceView.holder.surface?.isValid == true) surfaceCreated(surfaceView.holder)
}
private fun onBottomGameTouch(event: MotionEvent): Boolean {
if (pipUi) return true
if (!event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) return false
notePress(event)
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
drawerControllerActive = false
gestureTouchStreamGate.reset()
}
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) return false
return onTouchEvent(event)
}
@androidx.compose.runtime.Composable
private fun SwappedTopPanel() {
val pages = bottomPages()
val swapBack = { putGameOnBottom(false) }
androidx.compose.foundation.layout.Box(
Modifier.fillMaxSize().background(androidx.compose.material3.MaterialTheme.colorScheme.background)
.pointerInput(Unit) { awaitPointerEventScope { while (true) awaitPointerEvent() } },
) {
if (secondScreenMode == SecondScreenMode.DESKTOP && com.droiddeck.launcher.session.BottomDesktop.available()) {
androidx.compose.ui.viewinterop.AndroidView(
factory = { context ->
com.droiddeck.launcher.ui.BottomDesktopPanel(context, null, { drawerOpen = true },
(({ tapSteamButton() }) to ({ tapQam() })).takeIf { SessionState.mode == SessionService.MODE_STEAM }, swapBack,
fullResolution = true)
},
modifier = Modifier.fillMaxSize(),
)
} else if (pages.isNotEmpty()) BottomDashboard(
pages, com.droiddeck.launcher.ui.SessionBottomTab.picked(SessionState.sessionId),
gameStarts = gameStarts,
onPage = { com.droiddeck.launcher.ui.SessionBottomTab.pick(SessionState.sessionId, it) },
onClose = null,
onMenu = { drawerOpen = true },
onSwap = swapBack,
strip = { pageId ->
com.droiddeck.launcher.ui.SessionBottomStrip(pageId) { if (::hud.isInitialized) hud.liveFps else null }
},
) else androidx.compose.material3.Button(onClick = swapBack, modifier = Modifier.align(androidx.compose.ui.Alignment.Center)) {
androidx.compose.material3.Text(getString(R.string.swap_screens))
}
}
}
private fun glassesOutputSize(): Pair<Int, Int>? {
if (glassesScreen == null || glasses.width <= 0 || glasses.height <= 0) return null
val panel = (if (glasses.sbs) glasses.width / 2 else glasses.width) to glasses.height
@@ -4405,6 +4610,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
runCatching { current.dismiss() }
}
if (target != null) {
bottomGame?.let { restoreTopOutput(it); runCatching { it.dismiss() } }
val screen = GlassesScreen(this, target, Glasses.outputHz(), this, Glasses.outputResolution())
glassesScreen = screen
applyOutputPacing()
@@ -4430,6 +4636,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
applyOutputPacing()
refreshSecondScreenDisplays()
applyCardboard(cardboard)
if (target == null) updateBottomGame()
}
private fun onGlassesSteamVr(now: SteamVr.Status) {
@@ -4541,6 +4748,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
closeSecondScreen(reset = false)
glassesScope.cancel()
glassesScreen?.let { screen -> glassesScreen = null; runCatching { screen.dismiss() } }
bottomGame?.let { screen -> bottomGame = null; runCatching { screen.dismiss() } }
headTracker?.stop()
if (::hud.isInitialized) hud.stop()
if (::memoryHud.isInitialized) memoryHud.stop()
@@ -4626,6 +4834,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private const val PAUSED_FRAME_REDRAW_MS = 150L
private const val SETTINGS_WATCH_MS = 1_000L
private const val SETTINGS_WATCH_CHECKS = 600
private const val BOTTOM_RECOVERY_MS = 1_000L
private const val BOTTOM_RECOVERY_TRIES = 3
private const val TAG = "SessionActivity"
private var startedScreens = 0
@Volatile private var activeInstallWorker: Any? = null
@@ -208,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
@@ -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
}
}
}
@@ -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>> {
@@ -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 {
@@ -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
}
@@ -14,6 +14,8 @@ 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
@@ -56,7 +58,10 @@ class DroidDeckHudHost(context: Context) {
if (!gpuName.isNullOrBlank()) handler.post { this@DroidDeckHudHost.gpuName = cleanGpuName(gpuName) }
if (window != null && window != lastWindow) {
lastWindow = window
handler.post { onPresentingWindowChanged?.invoke() }
handler.post {
onPresentingWindowChanged?.invoke()
applyShown()
}
}
}
@@ -174,8 +179,9 @@ class DroidDeckHudHost(context: Context) {
private fun applyShown() {
if (!running) return
val show = !hidden && !backgrounded
view?.visibility = if (show) View.VISIBLE else View.GONE
showing = show
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)
@@ -208,14 +214,20 @@ class DroidDeckHudHost(context: Context) {
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)
hud.setResolution(if (feed.outputWidth > 0 && feed.outputHeight > 0) buildString {
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 "")
} else ""
hud.setResolution(feedResolution.ifBlank { sessionResolution() })
val pid = feed.pid
if (pid > 0 && pid != protonPid) {
protonPid = pid
@@ -125,6 +125,7 @@ class DroidDeckHudView(context: Context) : View(context) {
private var accent = 0xFF1A9FFF.toInt()
private var surfaceRgb = 0x121417
private var headerMark: RectF? = null
private var headerWordmark: RectF? = null
private var chipRect: RectF? = null
var dock = DroidDeckHudDock.NONE
@@ -167,12 +168,9 @@ class DroidDeckHudView(context: Context) : View(context) {
color = colGraph
}
private val headerPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
private val wordmarkPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD)
}
private class Glyph(val x: Float, val baseline: Float, val text: String, val color: Int, val sizePx: Float, val sans: Boolean = false, val glow: Boolean = false) {
fun moved(dx: Float, dy: Float) = Glyph(x + dx, baseline + dy, text, color, sizePx, sans, glow)
private class Glyph(val x: Float, val baseline: Float, val text: String, val color: Int, val sizePx: Float, val glow: Boolean = false) {
fun moved(dx: Float, dy: Float) = Glyph(x + dx, baseline + dy, text, color, sizePx, glow)
}
private class Span(val text: String, val color: Int, val sizePx: Float, val glow: Boolean = false)
private class HudRow(val label: Span, val vals: List<Span>, val inline: Boolean = false)
@@ -523,7 +521,7 @@ class DroidDeckHudView(context: Context) : View(context) {
private fun rebuild() {
glyphs.clear(); tileRects.clear(); graphRect = null
headerMark = null; chipRect = null; dPanel = null; dDividerTop = -1f; tabRect = null; stripRect = null
headerMark = null; headerWordmark = null; chipRect = null; dPanel = null; dDividerTop = -1f; tabRect = null; stripRect = null
val s = snap
if (s == null) { contentW = 0f; contentH = 0f; return }
if (dock != DroidDeckHudDock.NONE) { buildDockTab(); return }
@@ -576,24 +574,18 @@ class DroidDeckHudView(context: Context) : View(context) {
private fun footerClock(): Boolean = showClockTime && size == DroidDeckHudSize.PILL
private fun measureSans(text: String, sizePx: Float): Float { wordmarkPaint.textSize = sizePx; return wordmarkPaint.measureText(text) }
private fun panelInset() = sp(8f)
private fun panelLeft() = sp(13f)
private fun contentLeft() = panelLeft() + sp(16f)
private fun addPanelHeader(left: Float, inner: Float): Pair<Float, Float> {
val wordPx = sp(10f); val clockPx = sp(9.5f); val gapH = sp(7f)
wordmarkPaint.textSize = wordPx
val markH = wordmarkPaint.fontMetrics.let { it.descent - it.ascent } * 0.95f
val clockPx = sp(9.5f); val gapH = sp(7f)
val wordH = sp(12f)
val markTop = inner + gapH
val markLeft = left - DroidDeckMark.inkLeftFor(markH)
headerMark = RectF(markLeft, markTop, markLeft + DroidDeckMark.widthFor(markH), markTop + markH)
val midY = markTop + markH / 2f
var x = markLeft + DroidDeckMark.inkRightFor(markH) + sp(6f)
wordmarkPaint.getTextBounds("DroidDeck", 0, 9, inkRect)
glyphs.add(Glyph(x, midY - inkRect.exactCenterY(), "DroidDeck", blend(colValue), wordPx, sans = true))
x += measureSans("DroidDeck", wordPx)
val wordW = WordmarkArt.widthFor(wordH)
headerWordmark = RectF(left, markTop, left + wordW, markTop + wordH)
val midY = markTop + wordH / 2f
var x = left + wordW
if (showClockTime) {
measurePaint.textSize = clockPx
measurePaint.getTextBounds("0", 0, 1, inkRect)
@@ -605,7 +597,7 @@ class DroidDeckHudView(context: Context) : View(context) {
glyphs.add(Glyph(x, base, t, blend(colDim), clockPx))
x += measure(t, clockPx)
}
dDividerTop = markTop + markH + gapH
dDividerTop = markTop + wordH + gapH
return Pair(dDividerTop + max(1f, density), x)
}
@@ -647,7 +639,7 @@ class DroidDeckHudView(context: Context) : View(context) {
}
var right = panel.right
for (g in glyphs) {
val paint = if (g.sans) wordmarkPaint else measurePaint
val paint = measurePaint
paint.textSize = g.sizePx
paint.getTextBounds(g.text, 0, g.text.length, inkRect)
if (inkRect.isEmpty) continue
@@ -706,6 +698,9 @@ class DroidDeckHudView(context: Context) : View(context) {
contentW = max(contentW, pad + w + pad)
}
private fun hasGpuStats(s: HudMetrics.Snapshot): Boolean =
s.gpuPercent != null || s.gpuTempC != null || s.gpuClockMhz != null
private fun buildFull(s: HudMetrics.Snapshot) {
val rowPx = sp(12f); val unitPx = rowPx * 0.62f
val pad = sp(10f); val lineGap = sp(4f); val lvGap = sp(8f)
@@ -717,7 +712,7 @@ class DroidDeckHudView(context: Context) : View(context) {
rows.add(HudRow(Span("DISP", colDisp, rowPx), listOf(Span(displayServer, colValue, rowPx))))
if (hdrState != DroidDeckHudHdr.NONE)
rows.add(HudRow(Span("HDR", colHdr, rowPx), hdrValue(rowPx)))
if (showGPU) {
if (showGPU && hasGpuStats(s)) {
val v = ArrayList<Span>()
v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx)
if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx)
@@ -728,9 +723,9 @@ class DroidDeckHudView(context: Context) : View(context) {
if (showCPU) {
val v = ArrayList<Span>()
v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx)
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx)
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
rows.add(HudRow(Span("CPU", colCpu, rowPx), v))
}
if (showVram && s.vramText() != null)
@@ -807,12 +802,13 @@ class DroidDeckHudView(context: Context) : View(context) {
"${fmt1(fpsAvg)} avg · ${lowText(lows.low1Fps) ?: "—"} 1%", false))
if (showFPS) tiles.add(Tile("FRAME", colDim, numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", valPx, unitPx),
"${fmt1(graphMinMs)} – ${fmt1(graphMaxMs)}", false))
if (showGPU) tiles.add(Tile("GPU", colGpu, numUnit(s.gpuPercent?.toString(), "%", valPx, unitPx),
if (showGPU && hasGpuStats(s)) tiles.add(Tile("GPU", colGpu, numUnit(s.gpuPercent?.toString(), "%", valPx, unitPx),
if (showGpuTemp && s.gpuTempC != null) HudMetrics.formatTemp(s.gpuTempC.toFloat(), tempDisplay, false)
else s.gpuClockMhz?.let { "${it}MHz" }, false))
if (showCPU) tiles.add(Tile("CPU", colCpu, numUnit(s.cpuPercent?.toString(), "%", valPx, unitPx),
listOfNotNull(if (showCpuTemp) s.cpuTempC?.let { HudMetrics.formatTemp(it.toFloat(), tempDisplay, false) } else null,
s.cpuClockMhz?.toString()).joinToString(" · ").ifBlank { null }, false))
listOfNotNull(s.cpuClockMhz?.let { "${it}MHz" },
if (showCpuTemp) s.cpuTempC?.let { HudMetrics.formatTemp(it.toFloat(), tempDisplay, false) } else null)
.joinToString(" · ").ifBlank { null }, false))
if (showVram && s.vramText() != null) tiles.add(Tile("VRAM", colVram, valueUnit(s.vramText()!!, valPx, unitPx), null, false))
if (showRAM) tiles.add(Tile("RAM", colRam, numUnit(s.ramPercent.roundToInt().toString(), "%", valPx, unitPx),
"${s.ramUsedText()} / ${s.ramTotalText()}", false))
@@ -889,7 +885,7 @@ class DroidDeckHudView(context: Context) : View(context) {
val gpuName = if (showGpuModel && gpuNameText().isNotBlank()) gpuModelSpans(stkPx, colDim, compact = true) else null
run {
val l = ArrayList<Span>()
if (showGPU) { l += Span("GPU ${s.gpuPercent ?: "—"}%", colGpu, stkPx) }
if (showGPU && s.gpuPercent != null) { l += Span("GPU ${s.gpuPercent}%", colGpu, stkPx) }
if (showCPU) { if (l.isNotEmpty()) l += Span(" · ", colDim, stkPx); l += Span("CPU ${s.cpuPercent ?: "—"}%", colCpu, stkPx) }
if (l.isNotEmpty()) stack.add(l)
}
@@ -1145,7 +1141,7 @@ class DroidDeckHudView(context: Context) : View(context) {
val left = ArrayList<HudRow>()
if (showGpuModel && gpuNameText().isNotBlank())
left.add(HudRow(Span("GPU", colGpu, rowPx), gpuModelSpans(rowPx, colValue)))
if (showGPU) {
if (showGPU && hasGpuStats(s)) {
val v = ArrayList<Span>()
v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx)
if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx)
@@ -1156,9 +1152,9 @@ class DroidDeckHudView(context: Context) : View(context) {
if (showCPU) {
val v = ArrayList<Span>()
v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx)
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx)
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
left.add(HudRow(Span("CPU", colCpu, rowPx), v))
}
if (showPerCore) {
@@ -1319,7 +1315,7 @@ class DroidDeckHudView(context: Context) : View(context) {
stripRect?.let { drawStrip(canvas, it) }
for (g in glyphs) {
val paint = if (g.sans) wordmarkPaint else drawPaint
val paint = drawPaint
paint.textSize = g.sizePx
paint.color = g.color
if (g.glow) paint.setShadowLayer(sp(6f), 0f, 0f, withAlpha(colGraph, 217))
@@ -1327,6 +1323,7 @@ class DroidDeckHudView(context: Context) : View(context) {
if (g.glow) paint.clearShadowLayer()
}
headerMark?.let { DroidDeckMark.draw(canvas, it.left, it.top, it.height(), blend(colValue), accent) }
headerWordmark?.let { WordmarkArt.draw(canvas, it.left, it.top, it.height(), blend(colValue), accent) }
graphRect?.let { drawGraph(canvas, it) }
@@ -1416,10 +1413,6 @@ class DroidDeckHudView(context: Context) : View(context) {
headerPaint.color = withAlpha(accent, 90)
c.drawRect(panel.left, dDividerTop, roundEdgeX(panel, dDividerTop, stroke), dividerBottom, headerPaint)
}
val halfRound = dRadius >= panel.height() / 2f - 0.5f
val wmH = if (halfRound) panel.height() * 0.92f else min(panel.height(), panel.width()) * 0.55f
DroidDeckMark.draw(c, panel.right - DroidDeckMark.widthFor(wmH) - (if (halfRound) panel.height() * 0.02f else sp(10f)),
panel.centerY() - wmH / 2f, wmH, Color.argb(20, 255, 255, 255), withAlpha(accent, 20))
c.restore()
if (stroke > 0f) {
val h = stroke / 2f
@@ -1,7 +1,9 @@
package com.droiddeck.launcher.hud
import android.os.Environment
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import kotlin.math.roundToInt
internal class MangoReadings(private val sessionDir: File, private val rootDir: File) {
class Cpu(val percent: Int, val perCore: IntArray)
@@ -48,6 +50,7 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
}
fun cpuTempC(): Int? {
externalCpuTemp()?.let { return it }
var sum = 0f
var count = 0
for (zone in LinuxRuntime.cpuTempZones()) {
@@ -58,6 +61,13 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
return if (count == 0) null else (sum / count).toInt()
}
/** Optional ADB helper feed: /sdcard/DroidDeck/cpu-temp, written from the host while a session runs. */
private fun externalCpuTemp(): Int? {
val file = File(Environment.getExternalStorageDirectory(), "DroidDeck/cpu-temp")
if (!file.isFile || System.currentTimeMillis() - file.lastModified() > CPU_TEMP_FRESH_MS) return null
return readFloat(file)?.takeIf { it.isFinite() && it in -20f..150f }?.roundToInt()
}
fun gpuPercent(): Int? {
val feed = fresh(File(sessionDir, "sys/kgsl-3d0/perf_now"))
val source = feed ?: LinuxRuntime.gpuLoadSource()?.let(::File) ?: return null
@@ -92,7 +102,8 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
return Memory((total - available) * 1024, total * 1024, (swapTotal - swapFree) * 1024, swapTotal * 1024)
}
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)
/** The KGSL total DroidDeck shares with the session (GpuMemComponent). */
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)?.takeIf { it > 0 }
fun battery(): Battery? {
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }
@@ -132,6 +143,7 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
const val VRAM_FILE = "run/droiddeck-hud/gpu-mem"
private const val FEED_FRESH_MS = 10_000L
private const val VRAM_FRESH_MS = 15_000L
private const val CPU_TEMP_FRESH_MS = 10_000L
private val WHITESPACE = Regex("\\s+")
private fun readLong(file: File): Long? = runCatching { file.readText().trim().toLong() }.getOrNull()
@@ -0,0 +1,54 @@
package com.droiddeck.launcher.hud
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import androidx.compose.ui.graphics.asAndroidPath
import androidx.compose.ui.graphics.vector.PathParser
internal object WordmarkArt {
const val BOX_X = 239.135f
const val BOX_Y = 120.02f
const val BOX_W = 1040.7f - 239.135f
const val BOX_H = 243.2f - 120.02f
const val MARK_SCALE = 0.527445f
const val LEFT_HALF = "M-31.98 0H56.055V40.489A71.81 71.81 0 0 0 56.055 183.231V223.72H-31.98Z"
const val RIGHT_HALF = "M71.885 0.28A111.86 111.86 0 0 1 71.885 223.44V183.234A71.81 71.81 0 0 0 71.885 40.486Z"
const val LETTERS =
"M361.45 241.36V160.13H387.02V241.36ZM387.02 196.73 376.32 188.38Q379.5 174.17 387.02 166.31Q394.54 158.46 407.91 158.46Q413.76 158.46 418.19 160.21Q422.62 161.97 425.96 165.65L410.75 184.87Q409.08 183.03 406.57 182.03Q404.07 181.02 400.89 181.02Q394.54 181.02 390.78 184.95Q387.02 188.88 387.02 196.73" +
"ZM467.91 243.2Q455.38 243.2 445.27 237.6Q435.15 232 429.3 222.31Q423.45 212.61 423.45 200.58Q423.45 188.54 429.3 179.02Q435.15 169.49 445.18 163.89Q455.21 158.29 467.91 158.29Q480.62 158.29 490.64 163.81Q500.67 169.32 506.52 178.93Q512.37 188.54 512.37 200.58Q512.37 212.61 506.52 222.31Q500.67 232 490.64 237.6Q480.62 243.2 467.91 243.2" +
"ZM467.91 219.97Q473.43 219.97 477.61 217.54Q481.79 215.12 484.04 210.69Q486.3 206.26 486.3 200.58Q486.3 194.9 483.96 190.63Q481.62 186.37 477.52 183.95Q473.43 181.52 467.91 181.52Q462.56 181.52 458.39 183.95Q454.21 186.37 451.87 190.72Q449.53 195.06 449.53 200.75Q449.53 206.26 451.87 210.69Q454.21 215.12 458.39 217.54Q462.56 219.97 467.91 219.97" +
"ZM523.4 241.36V160.13H548.98V241.36ZM536.27 148.93Q530.26 148.93 526.33 144.84Q522.4 140.74 522.4 134.89Q522.4 128.88 526.33 124.86Q530.26 120.85 536.27 120.85Q542.29 120.85 546.13 124.86Q549.98 128.88 549.98 134.89Q549.98 140.74 546.13 144.84Q542.29 148.93 536.27 148.93ZM599.95 243.03Q588.42 243.03 579.48 237.52Q570.54 232 565.44 222.47Q560.34 212.95 560.34 200.75Q560.34 188.54 565.44 179.02Q570.54 169.49 579.48 163.97Q588.42 158.46 599.95 158.46Q608.31 158.46 615.08 161.63Q621.85 164.81 626.28 170.41Q630.71 176.01 631.21 183.2V217.46Q630.71 224.65 626.36 230.41Q622.02 236.18 615.16 239.61Q608.31 243.03 599.95 243.03" +
"ZM604.47 219.97Q609.98 219.97 613.99 217.54Q618 215.12 620.34 210.77Q622.68 206.43 622.68 200.75Q622.68 195.06 620.43 190.8Q618.17 186.54 614.08 184.03Q609.98 181.52 604.63 181.52Q599.28 181.52 595.19 184.03Q591.09 186.54 588.67 190.88Q586.25 195.23 586.25 200.75Q586.25 206.26 588.59 210.61Q590.93 214.95 595.11 217.46Q599.28 219.97 604.47 219.97" +
"ZM646.75 241.36H621.68V219.46L625.53 199.74L621.18 180.02V120.02H646.75ZM683.19 241.36V218.29H712.44Q723.13 218.29 731.16 214.03Q739.18 209.77 743.53 201.58Q747.87 193.39 747.87 182.19Q747.87 170.99 743.44 162.97Q739.01 154.95 731.07 150.6Q723.13 146.26 712.44 146.26H682.35V123.36H712.77Q726.14 123.36 737.42 127.62Q748.71 131.88 757.15 139.82Q765.59 147.76 770.18 158.54Q774.78 169.32 774.78 182.36Q774.78 195.23 770.18 206.09Q765.59 216.96 757.23 224.81Q748.87 232.67 737.59 237.01Q726.31 241.36 713.11 241.36" +
"ZM665.47 241.36V123.36H691.71V241.36ZM827.6 243.2Q814.39 243.2 804.11 237.77Q793.83 232.33 787.98 222.64Q782.13 212.95 782.13 200.75Q782.13 188.54 787.9 178.93Q793.67 169.32 803.53 163.81Q813.39 158.29 825.76 158.29Q837.79 158.29 846.98 163.47Q856.18 168.65 861.44 177.85Q866.71 187.04 866.71 198.91Q866.71 201.08 866.46 203.5Q866.21 205.93 865.54 209.1L795.51 209.27V191.72L854.67 191.55L843.64 198.91Q843.47 191.89 841.47 187.29Q839.46 182.69 835.54 180.27Q831.61 177.85 825.92 177.85Q819.91 177.85 815.48 180.61Q811.05 183.36 808.63 188.38Q806.2 193.39 806.2 200.58Q806.2 207.77 808.79 212.86Q811.38 217.96 816.15 220.72Q820.91 223.48 827.43 223.48Q833.45 223.48 838.29 221.39Q843.14 219.3 846.82 215.12L860.86 229.16Q854.84 236.18 846.32 239.69Q837.79 243.2 827.6 243.2" +
"ZM916.68 243.2Q904.15 243.2 893.95 237.68Q883.75 232.17 877.9 222.47Q872.05 212.78 872.05 200.75Q872.05 188.54 877.99 178.93Q883.92 169.32 894.12 163.81Q904.31 158.29 917.02 158.29Q926.54 158.29 934.48 161.55Q942.42 164.81 948.6 171.33L932.22 187.71Q929.38 184.53 925.62 183.03Q921.86 181.52 917.02 181.52Q911.5 181.52 907.24 183.95Q902.98 186.37 900.55 190.63Q898.13 194.9 898.13 200.58Q898.13 206.26 900.55 210.61Q902.98 214.95 907.32 217.46Q911.67 219.97 917.02 219.97Q922.03 219.97 925.96 218.21Q929.88 216.46 932.73 213.28L948.94 229.66Q942.59 236.35 934.56 239.77Q926.54 243.2 916.68 243.2" +
"ZM1010.61 241.36 982.2 199.24 1010.45 160.13H1039.03L1004.93 204.09L1005.77 193.56L1040.7 241.36ZM958.63 241.36V120.02H984.21V241.36Z"
private fun parse(d: String): Path = PathParser().parsePathString(d).toPath().asAndroidPath()
private val letters by lazy { parse(LETTERS) }
private val leftHalf by lazy { parse(LEFT_HALF) }
private val rightHalf by lazy { parse(RIGHT_HALF) }
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
fun widthFor(height: Float): Float = height * BOX_W / BOX_H
fun draw(canvas: Canvas, left: Float, top: Float, height: Float, inkColor: Int, ballColor: Int) {
val k = height / BOX_H
canvas.save()
canvas.translate(left, top)
canvas.scale(k, k)
canvas.translate(-BOX_X, -BOX_Y)
paint.color = inkColor
canvas.drawPath(letters, paint)
canvas.translate(239.135f, 123.36f)
canvas.scale(MARK_SCALE, MARK_SCALE)
canvas.translate(31.98f, 0f)
canvas.drawPath(leftHalf, paint)
canvas.drawPath(rightHalf, paint)
paint.color = ballColor
canvas.drawCircle(63.98f, 111.86f, 55.98f, paint)
canvas.restore()
}
}
@@ -51,6 +51,15 @@ val PC_KEY_ROWS: List<List<PcKey>> = listOf(
val PC_MODIFIERS: Set<Int> = setOf(42, 54, 29, 97, 56, 100, 125)
// Sticky modifiers are excluded: hiding a locked modifier would leave it pressed forever.
val PC_KEY_HIDDEN_GROUPS: Map<String, Set<Int>> = mapOf(
"function" to ((59..68).toSet() + setOf(1, 87, 88)),
"nav" to setOf(110, 111, 102, 107, 104, 109),
"arrows" to setOf(103, 105, 108, 106),
)
val PC_KEY_GROUP_IDS: Map<Int, String> = mapOf(0 to "function", 1 to "nav", 2 to "arrows")
val PC_KEYS: Map<Int, PcKey> = PC_KEY_ROWS.flatten().associateBy { it.code }
fun pcKeyLabel(context: Context, code: Int): String {
@@ -17,13 +17,14 @@ object BattleNet {
const val PROGRAM = "/usr/local/bin/droiddeck-battlenet"
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null)
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null, val flavor: String? = null)
internal val TITLES = listOf(
Title("wow", "World of Warcraft", "WoW", shop = "world-of-warcraft-midnight", product = "wow"),
Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades", product = "wow_classic"),
Title("wow_classic_era", "World of Warcraft Classic", "WoWC", product = "wow_classic_era"),
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC", product = "wow_anniversary"),
Title("wow", "World of Warcraft", "WoW", shop = "world-of-warcraft-midnight", product = "wow", flavor = "_retail_"),
Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades", product = "wow_classic", flavor = "_classic_"),
Title("wow_classic_era", "World of Warcraft Classic", "WoWC", product = "wow_classic_era", flavor = "_classic_era_"),
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC", product = "wow_anniversary", flavor = "_anniversary_"),
Title("wow_forever", "World of Warcraft: Forever", "WoWF", shop = "world-of-warcraft-forever", product = "wowf", flavor = "_forever_"),
Title("diablo3", "Diablo III", "D3", shop = "diablo-iii", product = "d3"),
Title("d3cn", "Diablo III", "D3CN", shop = "diablo-iii"),
Title("s2", "StarCraft II", "S2", shop = "starcraft-ii", product = "s2"),
@@ -58,7 +59,7 @@ object BattleNet {
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"),
)
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" }
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" && it.code != "WoWF" }
fun notInstalled(title: Title, installedIds: Collection<String?>) =
installedIds.mapNotNull { id -> id?.let(::title)?.code }.none { it == title.code }
@@ -159,24 +160,56 @@ object BattleNet {
return if (base.isNotEmpty() && id.substringAfterLast('_') in LOCALES) TITLES.firstOrNull { it.uid == base } else null
}
internal fun titleForProduct(product: String): Title? {
val code = product.trim()
if (code.isEmpty()) return null
return TITLES.firstOrNull { it.product.equals(code, ignoreCase = true) } ?: TITLES.firstOrNull { it.code.equals(code, ignoreCase = true) }
}
fun games(context: Context): List<Game> {
val pfx = File(prefix(context), "pfx")
val agent = runCatching { productDbInstalls(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrNull()
val entries = installs(
runCatching { File(pfx, "system.reg").useLines { uninstallEntries(it) } }.getOrDefault(emptyList()),
runCatching { productDbEntries(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrNull(),
agent?.map { it.uid to it.path },
)
val found = LinkedHashMap<String, Game>()
val products = agent.orEmpty().filter { it.product.isNotEmpty() }.associate { it.uid.lowercase() to it.product }
val listed = LinkedHashMap<String, Triple<Title, String, File>>()
for ((uid, path) in entries) {
val title = title(uid)
val title = title(uid) ?: products[uid.lowercase()]?.let(::titleForProduct)
if (title == null) {
if (uid.lowercase() !in NOT_GAMES) Log.i(TAG, "not listed: $uid (no launch code known)")
continue
}
if (title.code in found) continue
if (title.code in listed) continue
val folder = hostFolder(context, path)?.takeIf { it.isDirectory } ?: continue
found[title.code] = Game(title.uid, title.name, title.code, folder, uid)
listed[title.code] = Triple(title, uid, folder)
}
return found.values.toList()
val saved = listed.mapValues { (code, _) -> com.droiddeck.launcher.session.SessionPrefs.battleNetFolder(context, code) }
val folders = ownFolders(listed.mapValues { it.value.first to it.value.third }, saved)
return listed.map { (code, found) ->
val folder = folders.getValue(code)
if (saved[code] != folder.path) com.droiddeck.launcher.session.SessionPrefs.setBattleNetFolder(context, code, folder.path)
Game(found.first.uid, found.first.name, code, folder, found.second)
}
}
internal fun ownFolders(games: Map<String, Pair<Title, File>>, saved: Map<String, String?>): Map<String, File> {
val out = HashMap<String, File>()
val taken = HashSet<File>()
fun options(title: Title, folder: File) = listOfNotNull(folder, title.flavor?.let { File(folder, it) }?.takeIf { it.isDirectory })
for ((code, game) in games) {
val keep = saved[code]?.let(::File)?.takeIf { it in options(game.first, game.second) && it !in taken } ?: continue
out[code] = keep
taken.add(keep)
}
for ((code, game) in games) {
if (code in out) continue
val pick = options(game.first, game.second).firstOrNull { it !in taken } ?: game.second
out[code] = pick
taken.add(pick)
}
return games.keys.associateWith { out.getValue(it) }
}
internal fun installs(registry: List<Pair<String, String>>, agent: List<Pair<String, String>>?): List<Pair<String, String>> {
@@ -250,17 +283,22 @@ object BattleNet {
return out.toString()
}
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>>? {
internal class AgentInstall(val uid: String, val path: String, val product: String)
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>>? = productDbInstalls(bytes)?.map { it.uid to it.path }
internal fun productDbInstalls(bytes: ByteArray): List<AgentInstall>? {
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrNull()?.filter { it.first == 1 }?.takeIf { it.isNotEmpty() } ?: return null
return installs.map { (_, start, end) ->
runCatching {
val install = fields(bytes, start, end)
val uid = install.firstOrNull { it.first == 1 }?.let { String(bytes, it.second, it.third - it.second) }
val product = install.firstOrNull { it.first == 2 }?.let { String(bytes, it.second, it.third - it.second) }.orEmpty()
val path = install.firstOrNull { it.first == 3 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
?.let { String(bytes, it.second, it.third - it.second) }
val installed = install.firstOrNull { it.first == 4 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
?.let { s -> varints(bytes, s.second, s.third)[1] }
if (uid.isNullOrEmpty() || path.isNullOrEmpty() || installed == 0L) null else uid to path
if (uid.isNullOrEmpty() || path.isNullOrEmpty() || installed == 0L) null else AgentInstall(uid, path, product)
}.getOrElse { return null }
}.filterNotNull()
}
@@ -200,6 +200,7 @@ object BwrapSpawner {
LIB_DIRS.map { File(rootfs, "$it/$name") }.firstOrNull { it.exists() }
private fun gpu(rootfs: String, root: File, env: MutableMap<String, String>): List<Bind>? {
env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock) }
val driver = runtimeLib(rootfs, "libvulkan_freedreno.so")
if (driver == null || !File("/dev/kgsl-3d0").exists()) return null
if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null
@@ -222,6 +223,28 @@ object BwrapSpawner {
return binds
}
private fun bridgeGpu(rootfs: String, root: File, env: MutableMap<String, String>, socket: String): List<Bind>? {
val driver = File(rootfs, "usr/local/lib/vkbridge/libvulkan_droidbridge.so")
if (!driver.isFile) { Log.w(TAG, "gpu: vkbridge session but no bridge ICD in the runtime"); return null }
val binds = ArrayList<Bind>()
binds.add(Bind(driver.canonicalPath, "$GPU_DIR/libvulkan_droidbridge.so"))
val sockDir = File(socket).parent ?: return null
binds.add(Bind(sockDir, sockDir))
val icd = File(root.parentFile, "vkbridge_icd.json")
val api = runCatching {
JSONObject(File(rootfs, "usr/local/share/vkbridge/droidbridge_icd.json").readText()).getJSONObject("ICD").getString("api_version")
}.getOrNull() ?: run { Log.w(TAG, "gpu: vkbridge session but the runtime's bridge manifest is unreadable"); return null }
icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_droidbridge.so\", \"api_version\": \"$api\"}}\n")
binds.add(Bind(icd.path, "$GPU_DIR/vkbridge_icd.json"))
env["VK_DRIVER_FILES"] = "$GPU_DIR/vkbridge_icd.json"
env["VK_ICD_FILENAMES"] = "$GPU_DIR/vkbridge_icd.json"
if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) {
env["MESA_LOADER_DRIVER_OVERRIDE"] = "zink"
env["GALLIUM_DRIVER"] = "zink"
}
return binds
}
private fun preload(session: List<Bind>, rootfs: String, env: MutableMap<String, String>): List<Bind> {
val libs = FileUtils.readString(File(rootfs, "etc/ld.so.preload"))?.lines()
?.map { it.trim() }?.filter { it.startsWith("/") && File(rootfs + it).isFile } ?: return emptyList()
@@ -251,12 +251,36 @@ class LinuxNetworkLinkComponent(
}
}
private fun localDnsServers(): Pair<List<String>, List<String>> {
val active = connectivity.activeNetwork?.let { connectivity.getNetworkCapabilities(it) }
if (active?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true) return Pair(emptyList(), emptyList())
val servers = LinkedHashSet<String>()
val gateways = LinkedHashSet<String>()
for (network in connectivity.allNetworks) {
val capabilities = connectivity.getNetworkCapabilities(network) ?: continue
if (!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) continue
if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) continue
val link = connectivity.getLinkProperties(network) ?: continue
for (address in link.dnsServers) {
if (address.isLinkLocalAddress || address.isLoopbackAddress || address.isAnyLocalAddress) continue
address.hostAddress?.substringBefore('%')?.let { servers.add(it) }
}
link.routes.firstOrNull {
it.isDefaultRoute && (it.gateway as? Inet4Address)?.let { g -> !g.isLoopbackAddress && !g.isAnyLocalAddress } == true
}?.gateway?.hostAddress?.substringBefore('%')?.let { gateways.add(it) }
}
val order = compareBy<String>({ if (it.contains(':')) 1 else 0 })
return Pair(servers.sortedWith(order), gateways.sortedWith(order))
}
private fun writeResolver(properties: LinkProperties?) {
val own = properties?.dnsServers.orEmpty()
.filter { !it.isLinkLocalAddress && !it.isLoopbackAddress && !it.isAnyLocalAddress }
.sortedBy { if (it is Inet4Address) 0 else 1 }
.mapNotNull { it.hostAddress?.substringBefore('%') }
val servers = (own + listOf("8.8.8.8", "1.1.1.1", "2001:4860:4860::8888")).distinct().take(6)
val (discovered, gateways) = localDnsServers()
val servers = (own + discovered + listOf("8.8.8.8", "1.1.1.1", "2001:4860:4860::8888") + gateways).distinct().take(6)
val text = buildString {
append("# Written by the app from the device's active network; edits are overwritten.\n")
for (server in servers) append("nameserver $server\n")
@@ -278,10 +278,42 @@ public final class LinuxRuntime {
return false;
}
static final String MALI_DEVICE = "/dev/mali0";
static final String[] DRM_RENDER_NODES = {
"/dev/dri/renderD128", "/dev/dri/renderD129", "/dev/dri/renderD130", "/dev/dri/renderD131",
};
public static String gpuStandIn(Context context) {
if (new File(KGSL_DEVICE).exists()) return KGSL_DEVICE;
if (!com.droiddeck.launcher.core.DeviceSupport.INSTANCE.vkBridge(context)) return null;
return bridgeStandIn(path -> new File(path).exists());
}
static String bridgeStandIn(java.util.function.Predicate<String> exists) {
if (exists.test(MALI_DEVICE)) return MALI_DEVICE;
for (String node : DRM_RENDER_NODES) if (exists.test(node)) return node;
return null;
}
public static String deviceNumbers(String path) {
try {
long dev = Os.stat(path).st_rdev;
long major = ((dev >> 8) & 0xfff) | ((dev >> 32) & ~0xfffL);
long minor = (dev & 0xff) | ((dev >> 12) & ~0xffL);
return major + ":" + minor;
} catch (ErrnoException e) {
return null;
}
}
private static void bindGpuNode(Context context, List<String> cmd) {
String standIn = gpuStandIn(context);
if (standIn == null) return;
boolean kgsl = standIn.equals(KGSL_DEVICE);
StructStat st;
try {
st = Os.stat(KGSL_DEVICE);
st = Os.stat(standIn);
} catch (ErrnoException e) {
return;
}
@@ -301,13 +333,14 @@ public final class LinuxRuntime {
Files.write(new File(drm, "dev").toPath(),
(major + ":" + minor + "\n").getBytes(StandardCharsets.UTF_8));
Files.write(new File(device, "uevent").toPath(),
"DRIVER=kgsl-3d0\nMODALIAS=platform:kgsl-3d0\n".getBytes(StandardCharsets.UTF_8));
(kgsl ? "DRIVER=kgsl-3d0\nMODALIAS=platform:kgsl-3d0\n" : "DRIVER=mali\nMODALIAS=platform:mali\n")
.getBytes(StandardCharsets.UTF_8));
File subsystem = new File(device, "subsystem");
if (!Files.isSymbolicLink(subsystem.toPath())) {
Os.symlink("/sys/bus/platform", subsystem.getPath());
}
File driver = new File(device, "driver");
if (!Files.isSymbolicLink(driver.toPath())) {
if (kgsl && !Files.isSymbolicLink(driver.toPath())) {
Os.symlink("/sys/bus/platform/drivers/msm_drm", driver.getPath());
}
} catch (IOException | ErrnoException e) {
@@ -315,7 +348,7 @@ public final class LinuxRuntime {
}
bind(cmd, new File(base, "sys").getPath() + ":/sys/dev/char");
bind(cmd, dri.getPath() + ":/dev/dri");
bind(cmd, KGSL_DEVICE + ":/dev/dri/" + node);
bind(cmd, standIn + ":/dev/dri/" + node);
bindDrmClass(base, cmd, node, major + ":" + minor);
}
@@ -130,7 +130,8 @@ public final class LinuxRuntimeInstaller {
}
if (!owner) return join(job, listener);
try {
job.ok = installOnce(context.getApplicationContext(), release, new ProgressListener() {
Context app = context.getApplicationContext();
ProgressListener progress = new ProgressListener() {
@Override public void onProgress(String stage, int percent) {
onProgress(Step.OTHER, stage, percent);
}
@@ -141,7 +142,10 @@ public final class LinuxRuntimeInstaller {
job.percent = percent;
for (ProgressListener l : job.listeners) l.onProgress(step, stage, percent);
}
});
};
boolean desktop = DesktopCatalog.INSTANCE.desktopInstalled(app);
job.ok = installOnce(app, release, progress);
if (job.ok && desktop) keepDesktop(app, progress);
return job.ok;
} finally {
synchronized (JOB_LOCK) {
@@ -151,6 +155,28 @@ public final class LinuxRuntimeInstaller {
}
}
private static void keepDesktop(Context context, ProgressListener progress) {
String problem;
try {
problem = DesktopCatalog.INSTANCE.install(context, DesktopCatalog.INSTANCE.desktopEntry(context), progress);
} catch (RuntimeException e) {
problem = e.toString();
}
if (problem == null) {
Log.i(TAG, "desktop installed again for the new runtime");
return;
}
Log.w(TAG, "desktop not installed again for the new runtime: " + problem);
boolean started = false;
for (DesktopCatalog.Entry entry : DesktopCatalog.INSTANCE.interrupted(context)) {
if (DesktopCatalog.DESKTOP_ID.equals(entry.getId())) started = true;
}
if (!started) return;
String undone = DesktopCatalog.INSTANCE.removeDesktop(context, progress);
if (undone == null) Log.i(TAG, "rolled back the partial desktop install");
else Log.w(TAG, "could not roll back the partial desktop install: " + undone);
}
public static boolean isInstalling() {
synchronized (JOB_LOCK) {
return running != null && !running.removal && !running.maintenance;
@@ -61,7 +61,9 @@ object BottomDesktop {
/** The proot to freeze with the session when it pauses. */
val suspendPid: Int get() = guestPid
private var guestGeneration = 0
private var outputSize = 0 to 0
var outputSize = 0 to 0
private set
private var attachedSurface: Surface? = null
private var cursorShown = false
/** The session generation whose launch the running compositor and guest belong to; -1 when none. */
private var owner = -1
@@ -97,16 +99,8 @@ object BottomDesktop {
fun available(): Boolean =
launch?.installed == true && SessionState.running && SessionState.mode != SessionService.MODE_DESKTOP
/**
* The desktop renders below the panel's resolution: about 720 pixels on the short side keeps
* Plasma's text big enough to touch and its software rendering cheap. A running desktop keeps its size.
*/
fun outputSizeFor(width: Int, height: Int): Pair<Int, Int> {
if ((state == State.STARTING || state == State.RUNNING) && outputSize.first > 0) return outputSize
if (width <= 0 || height <= 0) return 0 to 0
val scale = maxOf(1f, Math.round(minOf(width, height) / TARGET_SHORT_SIDE * 2f) / 2f)
return ((width / scale).toInt() and 1.inv()) to ((height / scale).toInt() and 1.inv())
}
fun outputSizeFor(width: Int, height: Int, fullResolution: Boolean = false): Pair<Int, Int> =
desktopOutputSize(width, height, fullResolution, TARGET_SHORT_SIDE)
fun addListener(listener: () -> Unit) { listeners.add(listener) }
@@ -148,6 +142,7 @@ object BottomDesktop {
appContext = context.applicationContext
owner = current.generation
outputSize = width to height
attachedSurface = surface
val dir = File(current.sessionDir, "bottom-desktop").apply { mkdirs() }
val msg = Message.obtain(null, Comp.MSG_ATTACH).apply {
arg1 = owner
@@ -169,7 +164,19 @@ object BottomDesktop {
}
}
fun detach() {
fun resize(surface: Surface, width: Int, height: Int) {
if (surface !== attachedSurface || width <= 0 || height <= 0 || outputSize == (width to height)) return
outputSize = width to height
pendingAttach?.data?.apply {
putInt(Comp.KEY_WIDTH, width)
putInt(Comp.KEY_HEIGHT, height)
}
service?.let { send(it, Message.obtain(null, Comp.MSG_RESIZE, width, height)) }
}
fun detach(surface: Surface? = null) {
if (surface != null && attachedSurface != null && surface !== attachedSurface) return
attachedSurface = null
pendingAttach = null
service?.let { send(it, Message.obtain(null, Comp.MSG_DETACH)) }
}
@@ -351,3 +358,9 @@ object BottomDesktop {
}, "bottom-desktop-start").start()
}
}
internal fun desktopOutputSize(width: Int, height: Int, fullResolution: Boolean, targetShortSide: Float): Pair<Int, Int> {
if (width <= 0 || height <= 0) return 0 to 0
val scale = if (fullResolution) 1f else maxOf(1f, Math.round(minOf(width, height) / targetShortSide * 2f) / 2f)
return ((width / scale).toInt() and 1.inv()) to ((height / scale).toInt() and 1.inv())
}
@@ -7,6 +7,7 @@ import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.gpu.AppVulkan
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.github.luben.zstd.ZstdInputStream
@@ -638,29 +639,31 @@ object ComponentsManager {
}
fun swap(context: Context, protonId: String, file: String): String = synchronized(lock) {
fun swap(context: Context, protonId: String, file: String, auto: Boolean = false): String = synchronized(lock) {
val p = proton(context, protonId)
val wcp = File(packagesDir(context), safeName(file))
val info = packageInfo(context, wcp)
val state = loadState(context)
if (inUse(context, p)) {
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version))
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
.apply { if (auto) put("auto", true) })
saveState(context, state)
return context.getString(R.string.cmgr_swap_queued, LABEL[info.comp], info.version, p.name)
}
applyPackage(context, p, info, wcp, state)
applyPackage(context, p, info, wcp, state, auto)
state.sub("queued").optJSONObject(p.id)?.remove(info.comp)
saveState(context, state)
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
}
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject) {
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject, auto: Boolean = false) {
ensureOriginal(context, p, info.comp, state)
val hashes = installFiles(context, p.dir, info.comp, wcp)
state.sub("active").sub(p.id).put(info.comp, JSONObject()
.put("file", wcp.name).put("label", info.version).put("protonVersion", p.version)
.put("files", JSONObject(hashes.filterKeys { owned(info.comp, it) } as Map<*, *>))
.put("at", System.currentTimeMillis() / 1000))
.put("at", System.currentTimeMillis() / 1000)
.apply { if (auto) put("auto", true) })
Log.i(TAG, "swapped ${info.comp} ${info.version} into ${p.name} ${p.version}")
}
@@ -708,7 +711,7 @@ object ComponentsManager {
applyOriginal(context, p, comp, v, File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp"), state)
} else {
val wcp = File(packagesDir(context), q.optString("file"))
applyPackage(context, p, packageInfo(context, wcp), wcp, state)
applyPackage(context, p, packageInfo(context, wcp), wcp, state, q.optBoolean("auto"))
}
done += "${LABEL[comp]} ${q.optString("label")} → ${p.name}"
}.onFailure { Log.w(TAG, "queued $comp for ${p.name}", it) }
@@ -1011,15 +1014,76 @@ object ComponentsManager {
internal fun forcedPackageWanted(activeFile: String?, protonVersionMatches: Boolean): Boolean =
activeFile.isNullOrEmpty() || !protonVersionMatches
internal fun bridgeDxvk(vk: AppVulkan?): ForcedPackage? = when {
vk == null -> null
!vk.atLeast(1, 1) -> null
!vk.atLeast(1, 3) -> ForcedPackage(emptySet(), "dxvk", DXVK_FOR_VULKAN_1_1, "Dxvk-Linux")
vk.shaderInt64 == false || (vk.maxPushConstants ?: 256) < 256 ->
ForcedPackage(emptySet(), "dxvk", DXVK_FOR_VULKAN_1_3_NO_INT64, "Dxvk-Linux")
else -> null
}
internal const val DXVK_FOR_VULKAN_1_1 = "dxvk-1.10.3-linux.wcp"
internal const val DXVK_FOR_VULKAN_1_3_NO_INT64 = "dxvk-2.6.2-linux.wcp"
internal fun autoDxvkUndoWanted(bridgeSession: Boolean, keepProtonDxvk: Boolean, vulkan: AppVulkan?, bridgeRule: ForcedPackage?): Boolean =
!bridgeSession || keepProtonDxvk || (vulkan != null && bridgeRule == null)
private fun dropQueuedAuto(context: Context, installed: List<Proton>) = synchronized(lock) {
val state = loadState(context)
var changed = false
for (p in installed) {
val q = state.optJSONObject("queued")?.optJSONObject(p.id) ?: continue
if (q.optJSONObject("dxvk")?.optBoolean("auto") == true) { q.remove("dxvk"); changed = true }
}
if (changed) saveState(context, state)
}
internal fun autoChoiceStale(entry: JSONObject?, wantedFile: String?): Boolean =
entry != null && entry.optBoolean("auto") && entry.optString("file") != wantedFile
internal fun catalogMatch(items: List<CatalogItem>, file: String, release: String): CatalogItem? =
items.firstOrNull { it.file == file && it.release == release }
fun ensureForcedPackages(context: Context): String? = ensureForcedPackages(
private val forcedLock = Any()
fun ensureForcedPackages(context: Context): String? = synchronized(forcedLock) { ensureForcedPackages(
context, GpuInfo.detect(),
{ file, release -> catalogItem(context, file, release) },
{ download(context, it) {} },
{ id, file -> swap(context, id, file) },
)
vulkan = AppVulkan.detect(context),
bridgeSession = com.droiddeck.launcher.core.DeviceSupport.vkBridge(context),
applyAuto = { id, file -> swap(context, id, file, auto = true) },
undoAuto = { id, comp -> undoAutoChoice(context, id, comp) },
keepProtonDxvk = SessionPrefs.bridgeProtonDxvk(context),
autoPossible = !com.droiddeck.launcher.core.DeviceSupport.adreno(),
) }
fun settleAutoDxvk(context: Context) {
val app = context.applicationContext
Thread({
runCatching { ensureForcedPackages(app) }
.onSuccess { if (it != null) Log.i(TAG, it) }
.onFailure { Log.w(TAG, "automatic DXVK", it) }
}, "auto-dxvk").start()
}
internal fun undoAutoChoice(context: Context, protonId: String, comp: String): String = synchronized(lock) {
val p = proton(context, protonId)
val state = loadState(context)
val entry = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
val sameProton = entry?.optString("protonVersion") == p.version
if (sameProton && originalFile(context, p, comp).isFile)
return restore(context, protonId, comp, safeName(p.version))
if (sameProton) {
Log.w(TAG, "${p.name}: its own ${LABEL[comp]} copy is gone; keeping ${entry?.optString("label")}")
return "${LABEL[comp]}: ${p.name} keeps ${entry?.optString("label")} (its own copy is gone)"
}
state.sub("active").optJSONObject(p.id)?.remove(comp)
saveState(context, state)
"${LABEL[comp]}: ${p.name} keeps its own copy"
}
internal fun ensureForcedPackages(
context: Context,
@@ -1027,16 +1091,35 @@ object ComponentsManager {
lookup: (file: String, release: String) -> CatalogItem?,
fetch: (CatalogItem) -> Unit,
apply: (protonId: String, file: String) -> String,
vulkan: AppVulkan? = null,
bridgeSession: Boolean = false,
applyAuto: (protonId: String, file: String) -> String = apply,
undoAuto: (protonId: String, comp: String) -> String = { _, _ -> "" },
keepProtonDxvk: Boolean = false,
autoPossible: Boolean = true,
): String? {
val rules = FORCED_PACKAGES.filter { it.matches(gpu) }
if (rules.isEmpty()) return null
val chooseDxvk = bridgeSession && !keepProtonDxvk
val bridgeRule = if (chooseDxvk) bridgeDxvk(vulkan) else null
val rules = FORCED_PACKAGES.filter { it.matches(gpu) }.map { it to false } + listOfNotNull(bridgeRule?.let { it to true })
if (rules.isEmpty() && !autoPossible) return null
val installed = protons(context)
val lines = mutableListOf<String>()
for (rule in rules) {
fun each(p: Proton, what: () -> String): String =
runCatching(what).getOrElse { e -> Log.w(TAG, "${p.name}: ${e.message}", e); "${p.name}: ${e.message ?: e.javaClass.simpleName}" }
if (autoPossible && autoDxvkUndoWanted(bridgeSession, keepProtonDxvk, vulkan, bridgeRule)) {
dropQueuedAuto(context, installed)
val state = loadState(context)
for (p in installed) {
val entry = state.optJSONObject("active")?.optJSONObject(p.id)?.optJSONObject("dxvk")
if (autoChoiceStale(entry, null)) lines.add(each(p) { undoAuto(p.id, "dxvk") })
}
}
for ((rule, auto) in rules) {
val state = loadState(context)
val targets = installed.filter { p ->
val active = state.optJSONObject("active")?.optJSONObject(p.id)?.optJSONObject(rule.comp)
forcedPackageWanted(active?.optString("file"), active?.optString("protonVersion") == p.version)
forcedPackageWanted(active?.optString("file"), active?.optString("protonVersion") == p.version) ||
(auto && autoChoiceStale(active, rule.file))
}
if (targets.isEmpty()) continue
val missing = missingPackage(context, rule, lookup, fetch)
@@ -1044,9 +1127,10 @@ object ComponentsManager {
lines.add(missing)
continue
}
lines.add(targets.joinToString("; ") { apply(it.id, rule.file) })
if (auto) lines.add("${vulkan?.label}: DXVK ${rule.file}")
lines.add(targets.joinToString("; ") { p -> if (auto) each(p) { applyAuto(p.id, rule.file) } else apply(p.id, rule.file) })
}
return lines.joinToString("; ").ifEmpty { null }
return lines.filter { it.isNotEmpty() }.joinToString("; ").ifEmpty { null }
}
private fun missingPackage(
@@ -171,6 +171,9 @@ object SessionFiles {
val optional = (arrayOf(
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
"usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so" to "usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so",
"usr/local/lib/vkbridge/libvulkan_droidbridge.so" to "usr/local/lib/vkbridge/libvulkan_droidbridge.so",
"usr/local/share/vkbridge/droidbridge_icd.json" to "usr/local/share/vkbridge/droidbridge_icd.json",
"usr/local/bin/droiddeck-vkbridge-smoke" to "usr/local/bin/droiddeck-vkbridge-smoke",
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
@@ -348,6 +348,32 @@ object SessionPrefs {
prefs(context).edit().putInt("hudOpacity", percent.coerceIn(HUD_OPACITY_RANGE)).apply()
}
const val PC_KEYBOARD_SIZE_DEFAULT = 47
val PC_KEYBOARD_SIZE_RANGE = 25..70
const val PC_KEYBOARD_OPACITY_DEFAULT = 100
val PC_KEYBOARD_OPACITY_RANGE = 30..100
fun pcKeyboardSize(context: Context): Int =
prefs(context).getInt("pcKeyboardSize", PC_KEYBOARD_SIZE_DEFAULT).takeIf { it in PC_KEYBOARD_SIZE_RANGE } ?: PC_KEYBOARD_SIZE_DEFAULT
fun setPcKeyboardSize(context: Context, percent: Int) {
prefs(context).edit().putInt("pcKeyboardSize", percent.coerceIn(PC_KEYBOARD_SIZE_RANGE)).apply()
}
fun pcKeyboardOpacity(context: Context): Int =
prefs(context).getInt("pcKeyboardOpacity", PC_KEYBOARD_OPACITY_DEFAULT).takeIf { it in PC_KEYBOARD_OPACITY_RANGE } ?: PC_KEYBOARD_OPACITY_DEFAULT
fun setPcKeyboardOpacity(context: Context, percent: Int) {
prefs(context).edit().putInt("pcKeyboardOpacity", percent.coerceIn(PC_KEYBOARD_OPACITY_RANGE)).apply()
}
fun pcKeyboardHiddenKeys(context: Context): Set<String> =
idList(prefs(context).getString("pcKeyboardHiddenKeys", null)).toSet()
fun setPcKeyboardHiddenKeys(context: Context, hidden: Set<String>) {
prefs(context).edit().putString("pcKeyboardHiddenKeys", hidden.joinToString(",")).apply()
}
fun droidDeckHudConfig(context: Context): String? = prefs(context).getString("__KEEP_droidDeckHud__", null)
fun setDroidDeckHudConfig(context: Context, config: String) {
@@ -746,6 +772,29 @@ object SessionPrefs {
fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true)
@JvmStatic
fun vkBridge(context: Context): Boolean = prefs(context).getBoolean("vkBridge", com.droiddeck.launcher.core.DeviceSupport.mali())
fun setVkBridge(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("vkBridge", on).apply()
}
@JvmStatic
fun bridgeProtonDxvk(context: Context): Boolean = prefs(context).getBoolean("bridgeProtonDxvk", false)
fun setBridgeProtonDxvk(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("bridgeProtonDxvk", on).apply()
}
fun vkBridgeSafe(context: Context): Boolean = prefs(context).getBoolean("vkBridgeSafe", true)
fun setVkBridgeSafe(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("vkBridgeSafe", on).apply()
}
@JvmStatic
fun vkBridgeMode(context: Context): String = if (vkBridgeSafe(context)) "safe" else "performance"
fun setZinkLazy(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("zinkLazy", on).apply()
}
@@ -841,6 +890,9 @@ object SessionPrefs {
fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false)
fun setBattleNetNoSteamSet(context: Context) { prefs(context).edit().putBoolean("battleNetNoSteamSet", true).apply() }
fun battleNetFolder(context: Context, code: String): String? = prefs(context).getString("battleNetFolder:$code", null)
fun setBattleNetFolder(context: Context, code: String, path: String) { prefs(context).edit().putString("battleNetFolder:$code", path).apply() }
fun clearCachedApps(context: Context): Boolean = prefs(context).getBoolean("clearCachedApps", false)
fun setClearCachedApps(context: Context, on: Boolean) { prefs(context).edit().putBoolean("clearCachedApps", on).apply() }
@@ -70,6 +70,7 @@ class SessionService : Service() {
private val mainHandler = Handler(Looper.getMainLooper())
private var suspendController: SessionSuspendController? = null
private val steamDownloadMonitor = SteamDownloadMonitor()
private val downloadMonitorExecutor = java.util.concurrent.Executors.newSingleThreadExecutor { Thread(it, "steam-download-monitor").apply { isDaemon = true } }
private var downloadMonitorTask: Runnable? = null
private var downloadActive = false
private var clientInstallActive = false
@@ -346,7 +347,7 @@ class SessionService : Service() {
screenOn = readScreenOn()
manualPauseRequested = false
suspendDownloadNow = false
steamDownloadMonitor.reset()
runOnDownloadMonitor { steamDownloadMonitor.reset() }
downloadActive = false
clientInstallActive = false
steamSleepToken = null
@@ -371,9 +372,10 @@ class SessionService : Service() {
SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI)
SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL)
com.droiddeck.launcher.stores.battlenet.BattleNetClient.clearRequests(LinuxRuntime.sessionRoot(this))
synchronized(stopLock) {
val gen = synchronized(stopLock) {
SessionState.steamClientArch = null
SessionState.running = true
++sessionGen
}
if (SessionState.stopRequested) {
stopSession(0)
@@ -384,7 +386,6 @@ class SessionService : Service() {
SessionState.guestPid = -1
SessionEvents.transition(SessionPhase.STARTING_GUEST, "service.started", mapOf("mode" to SessionState.mode))
com.droiddeck.launcher.wayland.CompositorHost.newSession()
val gen = ++sessionGen
SessionPrefs.backgroundAppLimit(this).takeIf { it != com.droiddeck.launcher.core.BackgroundAppLimit.OFF }
?.let { com.droiddeck.launcher.core.BackgroundAppLimit.applyAsync(this, it) }
if (SessionPrefs.clearCachedApps(this)) clearCachedApps()
@@ -440,7 +441,7 @@ class SessionService : Service() {
LinuxRuntime.writeAccounts(this)
} catch (e: Exception) {
Log.e(TAG, "could not write the guest's passwd/group", e)
stopSession(-1)
stopSession(-1, gen)
return
}
@@ -467,8 +468,8 @@ class SessionService : Service() {
} else {
val message = getString(R.string.session_proot_missing)
Log.e(TAG, "$message (pack ready=$prootPack)")
SessionEvents.fail("PROOT_MISSING", message, -1)
stopSession(-1)
failSession(gen, "PROOT_MISSING", message, -1)
stopSession(-1, gen)
return
}
}
@@ -488,7 +489,7 @@ class SessionService : Service() {
GameEnvironmentStore.publish(this)
} catch (e: Exception) {
Log.e(TAG, "could not publish the game environment", e)
stopSession(-1)
stopSession(-1, gen)
return
}
val sessionLog = File(sessionDir, "session.log")
@@ -522,6 +523,7 @@ class SessionService : Service() {
components.add(encoder)
guest.add("BL_VENC_SOCKET=" + encoder.socket.absolutePath)
}
startVkBridge(guest, sessionDir)
guest.add("BL_WIDTH=" + size.first)
guest.add("BL_HEIGHT=" + size.second)
@@ -586,7 +588,7 @@ class SessionService : Service() {
val program = SessionState.program
if (program.isNullOrEmpty()) {
Log.e(TAG, "run mode without a program")
stopSession(65)
stopSession(65, gen)
return
}
guest.add(program)
@@ -681,7 +683,7 @@ class SessionService : Service() {
}
val program = programStatus(sessionRoot)
Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "")
stopSession(program ?: status ?: -1)
stopSession(program ?: status ?: -1, gen)
}, null, sessionLog.takeIf { "PROOT_PROFILE=1" in hostEnv.asArray() })
Log.i(TAG, "session pid $pid, log ${sessionLog.path}")
if (gen != sessionGen || !SessionState.running) {
@@ -703,8 +705,8 @@ class SessionService : Service() {
SessionEvents.guestStarted(pid)
} else {
SessionEvents.record("guest.start_failed", mapOf("pid" to pid))
SessionEvents.fail("GUEST_START_FAILED", "The guest process could not be started", pid)
stopSession(-1)
failSession(gen, "GUEST_START_FAILED", "The guest process could not be started", pid)
stopSession(-1, gen)
return
}
if (gen == sessionGen && SessionState.running) {
@@ -811,7 +813,7 @@ class SessionService : Service() {
?: SessionPrefs.androidDriver(this),
linuxDriverId,
)
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
if (!com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)) LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
val tuOverride = tuDebugOverride()
val tuDriver = sysmemDriver(linuxDriverId)
@@ -866,6 +868,27 @@ class SessionService : Service() {
private fun noSteamGame(): Boolean =
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
private fun startVkBridge(guest: MutableList<String>, sessionDir: File) {
if (!com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)) return
val socket = File(filesDir, "vkbridge/server.sock")
val bridge = com.droiddeck.launcher.gpu.VkBridgeComponent(socket, File(sessionDir, "vkbridge-server.log"))
bridge.attach(this)
components.add(bridge)
com.droiddeck.launcher.gpu.ClockLogComponent(File(sessionDir, "vkbridge-clocks.log")).let {
it.attach(this)
components.add(it)
}
guest.add("BL_VKBRIDGE=1")
guest.add("VKBRIDGE_SOCKET=" + socket.path)
guest.add("VKBRIDGE_CLIENT_LOG=" + File(sessionDir, "vkbridge-client.log").path)
guest.add("VKBRIDGE_MODE=" + SessionPrefs.vkBridgeMode(this))
LinuxRuntime.gpuStandIn(this)?.let { node ->
guest.add("BL_DRM_STANDIN=$node")
LinuxRuntime.deviceNumbers(node)?.let { guest.add("VKBRIDGE_DRM_RENDER=$it") }
}
Log.i(TAG, "vkbridge: on (${com.droiddeck.launcher.core.DeviceSupport.gpuName(this)}, ${SessionPrefs.vkBridgeMode(this)} mode), socket $socket")
}
private fun startAudio(guest: MutableList<String>, sessionDir: File, directAudioPack: Boolean): PulseAudioComponent {
val wantsDirectAudio = directAudioPack &&
(SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) &&
@@ -1865,11 +1888,22 @@ class SessionService : Service() {
}, "tracer-priority").start()
}
private fun stopSession(status: Int) {
cancelQueuedSteamGame()
gameExitWatchToken++
private fun failSession(gen: Int, code: String, message: String, status: Int?) {
synchronized(stopLock) {
if (gen == sessionGen) SessionEvents.fail(code, message, status)
}
}
private fun stopSession(status: Int, gen: Int? = null) {
if (gen != null && gen != sessionGen) {
Log.i(TAG, "ignoring a stop from session $gen; session $sessionGen is current")
return
}
completeNativeSleep()
val (ended, endedArch) = synchronized(stopLock) {
if (gen != null && gen != sessionGen) return
cancelQueuedSteamGame()
gameExitWatchToken++
if (!SessionState.running) return
SessionEvents.record("guest.exited", mapOf("status" to status))
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
@@ -1979,6 +2013,9 @@ class SessionService : Service() {
(getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager)?.unregisterDisplayListener(displayListener)
displayListenerRegistered = false
}
downloadMonitorTask?.let(mainHandler::removeCallbacks)
downloadMonitorTask = null
downloadMonitorExecutor.shutdown()
super.onDestroy()
}
@@ -2102,12 +2139,20 @@ class SessionService : Service() {
SessionState.running && SessionState.mode == MODE_STEAM && suspendPolicy != SessionPrefs.SUSPEND_NEVER &&
(steamDownloadsInBackground || !SessionState.firstFrameSeen)
private fun runOnDownloadMonitor(task: () -> Unit) {
try {
downloadMonitorExecutor.execute(task)
} catch (e: java.util.concurrent.RejectedExecutionException) {
Log.d(TAG, "download monitor already shut down")
}
}
private fun updateDownloadMonitoring() {
if (!downloadWatchWanted()) {
val wasActive = downloadActive
downloadMonitorTask?.let(mainHandler::removeCallbacks)
downloadMonitorTask = null
steamDownloadMonitor.reset()
runOnDownloadMonitor { steamDownloadMonitor.reset() }
downloadActive = false
if (clientInstallActive) SessionEvents.record("steam.client_download", mapOf("active" to false))
clientInstallActive = false
@@ -2129,18 +2174,30 @@ class SessionService : Service() {
val wasInstalling = clientInstallActive
clientInstallActive = !SessionState.firstFrameSeen &&
(clientInstallActive || SteamDownloadMonitor.clientInstallPending(root))
downloadActive = clientInstallActive || steamDownloadsInBackground && steamDownloadMonitor.poll(
root,
receivedBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid()),
client = SessionState.steamClientArch,
mounts = steamLibraryMounts,
)
if (wasInstalling != clientInstallActive) {
SessionEvents.record("steam.client_download", mapOf("active" to clientInstallActive))
val receivedBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid())
val client = SessionState.steamClientArch
val mounts = steamLibraryMounts
val self = this
val finish = { monitored: Boolean ->
if (downloadMonitorTask === self) {
downloadActive = clientInstallActive || monitored
if (wasInstalling != clientInstallActive) {
SessionEvents.record("steam.client_download", mapOf("active" to clientInstallActive))
}
if (wasActive != downloadActive) refreshNotification()
updateSuspendPolicy()
mainHandler.postDelayed(self, DOWNLOAD_POLL_MS)
}
}
if (clientInstallActive || !steamDownloadsInBackground) {
finish(false)
return
}
runOnDownloadMonitor {
val monitored = runCatching { steamDownloadMonitor.poll(root, receivedBytes = receivedBytes, client = client, mounts = mounts) }
.getOrDefault(false)
mainHandler.post { finish(monitored) }
}
if (wasActive != downloadActive) refreshNotification()
updateSuspendPolicy()
mainHandler.postDelayed(this, DOWNLOAD_POLL_MS)
}
}
downloadMonitorTask = poll
@@ -93,6 +93,7 @@ object SessionState {
@Volatile var secondScreenDisplay = -1
@Volatile var secondScreenAutoOpened = false
@Volatile var secondScreenProvisional = false
@Volatile var gameOnBottom = false
@Volatile var steamLibraryMounts: Map<String, java.io.File> = emptyMap()
@@ -17,7 +17,7 @@ object SettingsReset {
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition", "railLabels",
"stretch16x9", "picturePosition", "railLabels", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.session
import android.content.Context
import android.os.storage.StorageManager
import com.droiddeck.launcher.R
import com.droiddeck.launcher.files.StorageRoots
import com.droiddeck.launcher.frontend.AddedGames
import java.io.File
import org.json.JSONArray
@@ -49,15 +50,12 @@ object SteamLibraries {
class Refused(val reason: String) : AddResult()
}
fun add(context: Context, path: String, label: String = defaultLabel(context, File(path))): AddResult {
fun add(context: Context, picked: String, label: String? = null): AddResult {
val entries = list(context)
if (entries.size >= MAX) return AddResult.Refused(context.getString(R.string.libraries_full, MAX))
val path = innerLibrary(File(picked))?.path ?: picked
val host = canonical(File(path))
val taken = entries.map { canonical(it.host) } + listOfNotNull(
GameStorage.effective(context)?.let { canonical(File(it.path)) },
canonical(SessionPrefs.steamRoot(context, "arm64")),
)
if (taken.any { overlaps(it, host) }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
if (taken(context, entries).any { overlaps(it, host) }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
// Adding a Games folder itself is fine; a child of one would make it overlap and hide the rest of that folder.
if (AddedGames.roots(context).any { host.startsWith(canonical(it.host) + "/") }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
GameStorage.prepare(context, path)?.let { return AddResult.Refused(it) }
@@ -67,13 +65,70 @@ object SteamLibraries {
if (current.any { overlaps(canonical(it.host), host) }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
// A removed library's mount stays registered with Steam until its next session, so ids are never reused.
val next = maxOf(SessionPrefs.steamLibraryNextId(context), (current.maxOfOrNull { it.id.toInt() } ?: 0) + 1)
val entry = Entry(next.toString(), path, clean(label).ifEmpty { File(path).name })
val entry = Entry(next.toString(), path, clean(label ?: defaultLabel(context, File(path))).ifEmpty { File(path).name })
save(context, current + entry)
SessionPrefs.setSteamLibraryNextId(context, next + 1)
return AddResult.Added(entry)
}
}
private fun taken(context: Context, entries: List<Entry>): List<String> = entries.map { canonical(it.host) } + listOfNotNull(
GameStorage.effective(context)?.let { canonical(File(it.path)) },
canonical(SessionPrefs.steamRoot(context, "arm64")),
)
class Found(val path: String, val shown: String, val label: String, val games: Int)
/** Reads storage; call off the main thread. */
fun found(context: Context): List<Found> {
val entries = list(context)
val taken = taken(context, entries) + AddedGames.roots(context).map { canonical(it.host) }
val hits = ArrayList<Pair<File, Int>>()
for (root in StorageRoots.list(context)) {
if (!root.readable) continue
for (dir in candidates(rawView(root.dir), SCAN_DEPTH)) {
val games = gameCount(dir)
if (games > 0 && File(dir, "steamapps").canWrite() && taken.none { overlaps(it, canonical(dir)) }) hits += dir to games
}
}
val picked = ArrayList<Pair<File, Int>>()
for (hit in hits.sortedByDescending { it.second }) {
if (picked.none { overlaps(canonical(it.first), canonical(hit.first)) }) picked += hit
}
return picked.map { (dir, games) ->
val shown = File(storagePath(dir.path))
Found(dir.path, shown.path, defaultLabel(context, shown), games)
}
}
/** The FUSE view under /storage hides files other apps wrote unless DroidDeck has all files access; the raw card mount does not. */
private fun rawView(dir: File): File {
if (!dir.path.startsWith("/storage/") || dir.path.startsWith("/storage/emulated")) return dir
val raw = File("/mnt/media_rw/" + dir.path.removePrefix("/storage/"))
return if (raw.canRead() && raw.list() != null) raw else dir
}
internal fun innerLibrary(picked: File): File? {
if (gameCount(picked) > 0) return null
return candidates(picked, 1).filter { it != picked && gameCount(it) > 0 }.singleOrNull()
}
internal fun candidates(root: File, depth: Int): List<File> {
val out = arrayListOf(root)
var level = listOf(root)
repeat(depth) {
level = level.flatMap { dir ->
dir.listFiles { f -> f.isDirectory && !f.name.startsWith(".") && f.name != "steamapps" && !(dir == root && f.name == "Android") }
.orEmpty().sortedBy { it.name }
}.take(SCAN_LIMIT - out.size)
out += level
}
return out
}
internal fun gameCount(library: File): Int =
File(library, "steamapps").list()?.count { it.startsWith("appmanifest_") && it.endsWith(".acf") } ?: 0
fun rename(context: Context, id: String, label: String) {
val name = clean(label).takeIf { it.isNotEmpty() } ?: return
synchronized(lock) { save(context, list(context).map { if (it.id == id) Entry(it.id, it.path, name) else it }) }
@@ -84,17 +139,27 @@ object SteamLibraries {
synchronized(lock) { save(context, list(context).filterNot { it.id == id }) }
}
fun defaultLabel(context: Context, folder: File): String {
fun defaultLabel(context: Context, picked: File): String {
val folder = File(storagePath(picked.path))
val volume = try {
context.getSystemService(StorageManager::class.java)?.getStorageVolume(folder)?.getDescription(context)
} catch (e: Exception) {
null
}
val name = folder.name.ifEmpty { context.getString(R.string.gstore_folder) }
val parent = folder.parentFile
val named = if (folder.name.equals("Steam", true) && parent != null && !volumeRoot(parent)) parent else folder
val name = named.name.ifEmpty { context.getString(R.string.gstore_folder) }
return clean(if (volume.isNullOrBlank()) name else context.getString(R.string.gstore_folder_on_volume, name, volume))
}
private fun volumeRoot(dir: File): Boolean = dir.parent in setOf("/storage", "/mnt/media_rw", "/storage/emulated") || dir.parent == null
internal fun overlaps(a: String, b: String): Boolean = a == b || a.startsWith("$b/") || b.startsWith("$a/")
private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)
private fun storagePath(path: String): String = if (path.startsWith("/mnt/media_rw/")) "/storage/" + path.removePrefix("/mnt/media_rw/") else path
private fun canonical(file: File): String = storagePath(runCatching { file.canonicalPath }.getOrDefault(file.absolutePath))
private const val SCAN_DEPTH = 2
private const val SCAN_LIMIT = 4000
}
@@ -20,6 +20,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Menu
import androidx.compose.material.icons.outlined.SwapVert
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
@@ -84,10 +85,11 @@ fun BottomDashboard(
pages: List<BottomPage>,
remembered: String?,
onPage: (String) -> Unit,
onClose: () -> Unit,
onClose: (() -> Unit)?,
onMenu: (() -> Unit)?,
gameStarts: Int = 0,
strip: (@Composable (String?) -> Unit)? = null,
onSwap: (() -> Unit)? = null,
) {
val colors = MaterialTheme.colorScheme
var current by remember { mutableStateOf(pickBottomPage(remembered, pages.map { it.id })) }
@@ -100,7 +102,7 @@ fun BottomDashboard(
val labels = bottomTabsWithLabels(maxWidth.value, pages.size)
Column(Modifier.fillMaxSize().padding(horizontal = 12.dp, vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(Modifier.fillMaxWidth().height(48.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
BarButton(Icons.Outlined.Close, stringResource(R.string.deck_close), "bottom-close", onClose)
if (onClose != null) BarButton(Icons.Outlined.Close, stringResource(R.string.deck_close), "bottom-close", onClose)
Row(Modifier.weight(1f).horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
pages.forEach { p ->
PageTab(p, p.id == page?.id, labels) {
@@ -109,6 +111,7 @@ fun BottomDashboard(
}
}
}
if (onSwap != null) BarButton(Icons.Outlined.SwapVert, stringResource(R.string.swap_screens), "bottom-swap", onSwap)
if (onMenu != null) BarButton(Icons.Outlined.Menu, stringResource(R.string.touch_droiddeck_menu), "bottom-menu", onMenu)
}
strip?.invoke(page?.id)
@@ -4,6 +4,7 @@ import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Configuration
import android.graphics.Color
import android.os.Build
import android.os.SystemClock
import android.graphics.Typeface
import android.view.Gravity
@@ -13,6 +14,7 @@ import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowInsets
import android.graphics.RectF
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.platform.ComposeView
@@ -33,9 +35,11 @@ import com.droiddeck.launcher.session.BottomDesktop
@SuppressLint("ViewConstructor")
class BottomDesktopPanel(
context: Context,
onClose: () -> Unit,
onClose: (() -> Unit)?,
onMenu: (() -> Unit)?,
steamButtons: Pair<() -> Unit, () -> Unit>?,
onSwap: (() -> Unit)? = null,
private val fullResolution: Boolean = false,
) : LinearLayout(context), SurfaceHolder.Callback {
private lateinit var surfaceView: SurfaceView
private val area = FrameLayout(context).apply { clipChildren = true }
@@ -66,7 +70,7 @@ class BottomDesktopPanel(
setBackgroundColor(Color.BLACK)
isFocusable = true
isFocusableInTouchMode = true
addView(bar(onClose, onMenu, steamButtons), LayoutParams(-1, -2))
addView(bar(onClose, onMenu, steamButtons, onSwap), LayoutParams(-1, -2))
area.addView(keyboardHost)
addSurface()
area.addView(status, FrameLayout.LayoutParams(-1, -1))
@@ -83,7 +87,7 @@ class BottomDesktopPanel(
area.addView(surfaceView, 1, FrameLayout.LayoutParams(fullWidth.takeIf { it > 0 } ?: -1, fullHeight.takeIf { it > 0 } ?: -1))
}
private fun bar(onClose: () -> Unit, onMenu: (() -> Unit)?, steamButtons: Pair<() -> Unit, () -> Unit>?): View {
private fun bar(onClose: (() -> Unit)?, onMenu: (() -> Unit)?, steamButtons: Pair<() -> Unit, () -> Unit>?, onSwap: (() -> Unit)?): View {
val bar = LinearLayout(context).apply {
orientation = HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
@@ -91,7 +95,7 @@ class BottomDesktopPanel(
setBackgroundColor(Color.BLACK)
}
fun gap() = View(context).apply { layoutParams = LayoutParams(dp(6), 1) }
bar.addView(DeckControlsPanel.roundButton(context, "×", context.getString(R.string.deck_close), onClose))
onClose?.let { bar.addView(DeckControlsPanel.roundButton(context, "×", context.getString(R.string.deck_close), it)) }
title = TextView(context).apply {
textSize = 14f
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
@@ -106,6 +110,10 @@ class BottomDesktopPanel(
bar.addView(gap())
bar.addView(DeckControlsPanel.iconButton(context, R.drawable.ic_bottom_keyboard,
context.getString(R.string.second_show_keyboard)) { keyboardHost.toggle() })
onSwap?.let {
bar.addView(gap())
bar.addView(DeckControlsPanel.iconButton(context, R.drawable.ic_bottom_swap, context.getString(R.string.swap_screens), it))
}
onMenu?.let {
bar.addView(gap())
bar.addView(DeckControlsPanel.menuButton(context, it))
@@ -187,7 +195,9 @@ class BottomDesktopPanel(
addSurface()
return
}
if (attached) attach(surfaceView.holder)
if (!attached) return
attached = false
syncSurface(surfaceView.holder)
}
private fun showState() {
@@ -208,13 +218,28 @@ class BottomDesktopPanel(
if (w != fullWidth || h > fullHeight || !keyboardHost.shown) {
fullWidth = w
fullHeight = h
surfaceView.layoutParams = FrameLayout.LayoutParams(w, h)
val (desktopW, desktopH) = BottomDesktop.outputSizeFor(w, h, fullResolution)
val (fitW, fitH) = if (w - desktopW in 0..1 && h - desktopH in 0..1) desktopW to desktopH
else fitDesktop(w, h, desktopW, desktopH)
surfaceView.layoutParams = if (fitW == w && fitH == h) FrameLayout.LayoutParams(w, h)
else FrameLayout.LayoutParams(fitW, fitH, Gravity.CENTER_HORIZONTAL).apply { topMargin = (h - fitH) / 2 }
surfaceView.post { syncSurface(surfaceView.holder) }
}
pan()
}
private fun imeOverlap(): Int {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return 0
if (area.height < fullHeight) return 0
val ime = rootWindowInsets?.getInsets(WindowInsets.Type.ime())?.bottom ?: return 0
if (ime <= 0) return 0
val at = IntArray(2)
area.getLocationInWindow(at)
return (at[1] + area.height - (rootView.height - ime)).coerceIn(0, area.height)
}
private fun pan() {
val visible = area.height
val visible = area.height - imeOverlap()
val hidden = (fullHeight - visible).coerceAtLeast(0)
val anchor = if (directTouch) lastTouchY else trackpad.y
surfaceView.translationY = if (hidden == 0 || !keyboardHost.shown) 0f
@@ -223,24 +248,27 @@ class BottomDesktopPanel(
override fun surfaceCreated(holder: SurfaceHolder) = Unit
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
if (!attached) attach(holder)
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = syncSurface(holder)
override fun surfaceDestroyed(holder: SurfaceHolder) {
if (holder !== surfaceView.holder) return
attached = false
surfaceUsed = false
BottomDesktop.detach()
BottomDesktop.detach(holder.surface)
}
private fun attach(holder: SurfaceHolder) {
val frame = holder.surfaceFrame
val (width, height) = BottomDesktop.outputSizeFor(fullWidth.takeIf { it > 0 } ?: frame.width(),
fullHeight.takeIf { it > 0 } ?: frame.height())
private fun syncSurface(holder: SurfaceHolder) {
if (holder !== surfaceView.holder || fullWidth <= 0 || fullHeight <= 0 || !holder.surface.isValid) return
val (width, height) = BottomDesktop.outputSizeFor(fullWidth, fullHeight, fullResolution)
if (width <= 0 || height <= 0) return
val frame = holder.surfaceFrame
if (frame.width() != width || frame.height() != height) {
holder.setFixedSize(width, height)
val params = surfaceView.layoutParams
if (params.width == width && params.height == height) holder.setSizeFromLayout() else holder.setFixedSize(width, height)
return
}
if (attached) {
BottomDesktop.resize(holder.surface, width, height)
return
}
attached = true
@@ -299,7 +327,7 @@ class BottomDesktopPanel(
override fun onWheel(steps: Int) = BottomDesktop.sendScene(SCENE_WHEEL, steps)
override fun onScroll(dx: Float, dy: Float) {
val (outW, outH) = BottomDesktop.outputSizeFor(surfaceView.width, surfaceView.height)
val (outW, outH) = BottomDesktop.outputSize
scrollRestX += dx * outW / surfaceView.width.coerceAtLeast(1) * AXIS_UNITS_PER_PIXEL
scrollRestY += dy * outH / surfaceView.height.coerceAtLeast(1) * AXIS_UNITS_PER_PIXEL
val h = scrollRestX.toInt()
@@ -343,3 +371,11 @@ class BottomDesktopPanel(
const val TEXT_FIELD_TAP_MS = 1_000L
}
}
internal fun fitDesktop(areaW: Int, areaH: Int, desktopW: Int, desktopH: Int): Pair<Int, Int> {
if (areaW <= 0 || areaH <= 0 || desktopW <= 0 || desktopH <= 0) return areaW to areaH
val widthLimited = areaW.toLong() * desktopH <= areaH.toLong() * desktopW
val w = if (widthLimited) areaW else (desktopW.toLong() * areaH / desktopH).toInt()
val h = if (widthLimited) (desktopH.toLong() * areaW / desktopW).toInt() else areaH
return if (areaW - w <= 4 && areaH - h <= 4) areaW to areaH else w to h
}
@@ -0,0 +1,66 @@
package com.droiddeck.launcher.ui
import android.app.Activity
import android.app.Presentation
import android.graphics.Color
import android.os.Bundle
import android.view.Display
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.FrameLayout
class BottomGameScreen(
private val activity: Activity,
display: Display,
private val callback: SurfaceHolder.Callback,
private val onTouch: (MotionEvent) -> Boolean,
) : Presentation(activity, display) {
val surfaceView = SurfaceView(getContext())
val holder: SurfaceHolder get() = surfaceView.holder
val hz: Float get() = display.mode.refreshRate
init {
setCancelable(false)
setCanceledOnTouchOutside(false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val root = FrameLayout(context).apply { setBackgroundColor(Color.BLACK) }
root.addView(surfaceView, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
setContentView(root)
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
@Suppress("DEPRECATION")
window?.decorView?.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
surfaceView.setOnTouchListener { _, event -> onTouch(event) }
surfaceView.holder.addCallback(callback)
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean =
activity.dispatchKeyEvent(event) || super.dispatchKeyEvent(event)
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean =
activity.dispatchGenericMotionEvent(event) || super.dispatchGenericMotionEvent(event)
}
object GameScreenSwap {
fun wanted(
requested: Boolean,
activityStarted: Boolean,
sessionEnded: Boolean,
inPip: Boolean,
glassesOutput: Boolean,
bottomScreenFree: Boolean,
): Boolean = requested && activityStarted && !sessionEnded && !inPip && !glassesOutput && bottomScreenFree
}
@@ -27,7 +27,7 @@ import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
import java.io.File
private const val STRIP_FRAME_MS = 100L
private const val STRIP_FRAME_MS = 33L
private const val STRIP_METRICS_MS = 500L
private const val STRIP_TEMP_PLAIN = 0xFFF2F5F9.toInt()
@@ -96,7 +96,7 @@ private const val ELITE_MS = 1_000L
private const val ELITE_SEARCH_MS = 10_000L
private const val OUTPUT_SCAN_MS = 3_000L
private const val PERF_N = 60
private const val FRAME_MS = 100L
private const val FRAME_MS = 33L
private const val MINUTE_NS = 60_000_000_000L
private const val TEMP_PLAIN = 0xFFF2F5F9.toInt()
@@ -149,6 +149,10 @@ class FrontEndState(
val oscMode: String = SessionPrefs.OSC_AUTO,
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
val adreno: Boolean = true,
val vkBridge: Boolean = false,
val vkBridgeSafe: Boolean = true,
val bridgeProtonDxvk: Boolean = false,
val showPhantomGate: Boolean = false,
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER,
@@ -205,6 +209,9 @@ class FrontEndActions(
val onInstallPackage: (String) -> Unit,
val onRemovePackage: (String) -> Unit,
val onRuntime: () -> Unit,
val onVkBridge: (Boolean) -> Unit = {},
val onVkBridgeSafe: (Boolean) -> Unit = {},
val onBridgeProtonDxvk: (Boolean) -> Unit = {},
val onFrameGenPick: (FrameGen.Mode) -> Unit,
val onImportLossless: () -> Unit,
val onProtons: () -> Unit,
@@ -171,7 +171,7 @@ internal fun SetupPanel(
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val gpu = remember { com.droiddeck.launcher.gpu.GpuInfo.detect() }
val gpuOk = gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED
val gpuOk = gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED || s.vkBridge
val gpuName = remember { DeviceSupport.gpuName(ctx) }
val limitBlocks = PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
val signedIn = s.offlineAccount != null
@@ -232,7 +232,7 @@ internal fun SetupPanel(
val runtimeOk = s.ready && !s.busy && !s.removalPending
val checks = listOf(gpuOk, runtimeOk, !limitBlocks, signedIn)
val passing = checks.count { it }
var showChecks by rememberSaveable { mutableStateOf(false) }
var showChecks by rememberSaveable { mutableStateOf(s.vkBridge) }
Rise(0, Modifier.fillMaxSize()) {
Column(
modifier = Modifier.fillMaxSize().bumpers(
@@ -249,17 +249,49 @@ internal fun SetupPanel(
val gpuCheck: @Composable (Boolean) -> Unit = { divider ->
CheckRow(
if (gpuOk) CheckState.OK else CheckState.WARN,
when (gpu.support) {
com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_supported)
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested)
when {
gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_supported)
gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested)
s.vkBridge -> stringResource(R.string.setup_gpu_bridged)
else -> stringResource(R.string.setup_gpu_unsupported)
},
when (gpu.support) {
com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_detail, gpu.displayName(ctx), gpuName)
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested_detail, gpu.displayName(ctx), gpu.supportText(ctx).replaceFirstChar { it.lowercase() })
else -> stringResource(R.string.setup_gpu_unsupported_detail, gpuName)
else -> if (s.vkBridge) stringResource(R.string.setup_gpu_bridge_detail, gpuName)
else stringResource(R.string.setup_gpu_unsupported_detail, gpuName)
},
divider = divider || (!s.adreno && s.vkBridge),
action = if (s.adreno) null else { {
SecondaryButton(
stringResource(if (s.vkBridge) R.string.setup_gpu_bridge_on else R.string.setup_gpu_bridge_off),
enabled = !s.sessionRunning, compact = true, onClick = { a.onVkBridge(!s.vkBridge) },
)
} },
)
if (!s.adreno && s.vkBridge) CheckRow(
CheckState.OK,
stringResource(R.string.setup_bridge_safe),
stringResource(if (s.vkBridgeSafe) R.string.setup_bridge_safe_on_detail else R.string.setup_bridge_safe_off_detail),
divider = divider,
action = {
SecondaryButton(
stringResource(if (s.vkBridgeSafe) R.string.setup_bridge_safe_on else R.string.setup_bridge_safe_off),
enabled = !s.sessionRunning, compact = true, onClick = { a.onVkBridgeSafe(!s.vkBridgeSafe) },
)
},
)
if (!s.adreno && s.vkBridge) CheckRow(
CheckState.OK,
stringResource(R.string.setup_bridge_dxvk),
stringResource(if (s.bridgeProtonDxvk) R.string.setup_bridge_dxvk_proton_detail else R.string.setup_bridge_dxvk_auto_detail),
divider = divider,
action = {
SecondaryButton(
stringResource(if (s.bridgeProtonDxvk) R.string.setup_bridge_dxvk_proton else R.string.setup_bridge_dxvk_auto),
enabled = !s.sessionRunning, compact = true, onClick = { a.onBridgeProtonDxvk(!s.bridgeProtonDxvk) },
)
},
)
}
val runtimeCheck: @Composable (Boolean) -> Unit = { divider ->
@@ -75,6 +75,8 @@ class ModeSettings(
val gameStorage: String? = null,
val storageOptions: List<com.droiddeck.launcher.session.GameStorage.Option> = emptyList(),
val steamLibraries: List<com.droiddeck.launcher.session.SteamLibraries.Entry> = emptyList(),
val foundSteamLibraries: List<com.droiddeck.launcher.session.SteamLibraries.Found> = emptyList(),
val allFilesAccessMissing: Boolean = false,
val storageDiagnostics: Boolean = false,
val fexPreset: String? = null,
val forceSsbs: Boolean = false,
@@ -126,6 +128,8 @@ class ModeSettingsActions(
val onPickGameStorageFolder: () -> Unit = {},
val onStorageDiagnostics: (Boolean) -> Unit = {},
val onAddSteamLibrary: () -> Unit = {},
val onAddFoundSteamLibrary: (path: String) -> Unit = {},
val onAllowAllFilesAccess: () -> Unit = {},
val onRenameSteamLibrary: (id: String, label: String) -> Unit = { _, _ -> },
val onRemoveSteamLibrary: (id: String) -> Unit = {},
val onFexPreset: (String) -> Unit = {},
@@ -421,6 +425,19 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
}
}
}
if (s.steamLibraries.size < com.droiddeck.launcher.session.SteamLibraries.MAX) for (found in s.foundSteamLibraries) {
SettingsRow(
found.label,
stringResource(R.string.libraries_found_hint, pluralStringResource(R.plurals.mode_added_count, found.games, found.games), found.shown),
) {
SecondaryButton(stringResource(R.string.libraries_add_found), compact = true) { a.onAddFoundSteamLibrary(found.path) }
}
}
if (s.allFilesAccessMissing && s.steamLibraries.size < com.droiddeck.launcher.session.SteamLibraries.MAX) {
SettingsRow(stringResource(R.string.libraries_access_title), stringResource(R.string.libraries_access_hint)) {
SecondaryButton(stringResource(R.string.libraries_access_allow), compact = true, onClick = a.onAllowAllFilesAccess)
}
}
SettingsRow(
stringResource(R.string.libraries_add),
if (s.steamLibraries.size < com.droiddeck.launcher.session.SteamLibraries.MAX) stringResource(R.string.libraries_hint)
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.PC_KEY_HIDDEN_GROUPS
import com.droiddeck.launcher.input.PC_KEY_ROWS
import com.droiddeck.launcher.input.PC_MODIFIERS
import com.droiddeck.launcher.input.PcKey
@@ -35,6 +36,7 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.key
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
@@ -45,12 +47,14 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.nativeKeyCode
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
@@ -98,10 +102,17 @@ fun PcKeyboard(
}
LaunchedEffect(Unit) { runCatching { firstKey.requestFocus() } }
val prefsContext = LocalContext.current
remember { PcKeyboardPrefs.load(prefsContext) }
val hiddenCodes = PcKeyboardPrefs.hiddenKeys.flatMap { PC_KEY_HIDDEN_GROUPS[it].orEmpty() }.toSet()
val rows = PC_KEY_ROWS.map { row -> row.filter { it.code !in hiddenCodes } }.filter { it.isNotEmpty() }
BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) {
val rowHeight = ((maxHeight * 0.47f - 24.dp - 3.dp * 6 - 10.dp) / 6).coerceIn(24.dp, 44.dp)
val rowHeight = ((maxHeight * (PcKeyboardPrefs.size / 100f) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size)
.coerceIn(20.dp, 56.dp)
Box(
Modifier.fillMaxWidth()
.graphicsLayer { alpha = PcKeyboardPrefs.opacity / 100f }
.background(Color(0xE6101418), RoundedCornerShape(topStart = 14.dp, topEnd = 14.dp))
.border(1.dp, pal.line2, RoundedCornerShape(topStart = 14.dp, topEnd = 14.dp))
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume(); waitForUpOrCancellation()?.consume() } }
@@ -115,7 +126,7 @@ fun PcKeyboard(
Spacer(Modifier.width(8.dp))
HeaderButton(stringResource(R.string.pckb_hide), onClose)
}
PC_KEY_ROWS.forEachIndexed { r, row ->
rows.forEachIndexed { r, row ->
Row(horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.fillMaxWidth().height(rowHeight)) {
row.forEachIndexed { i, key ->
val state = mods[key.code] ?: MOD_OFF
@@ -126,11 +137,13 @@ fun PcKeyboard(
key.label.length == 1 && key.label[0].isLetter() && (shifted xor capsOn) -> key.label.uppercase()
else -> key.label
}
KeyCap(
label, key.weight, lit, locked = state == MOD_LOCKED,
modifier = if (r == 0 && i == 0) Modifier.focusRequester(firstKey) else Modifier,
onDown = { press(key) }, onUp = { release(key) },
)
key(key.code) {
KeyCap(
label, key.weight, lit, locked = state == MOD_LOCKED,
modifier = if (r == 0 && i == 0) Modifier.focusRequester(firstKey) else Modifier,
onDown = { press(key) }, onUp = { release(key) },
)
}
}
}
}
@@ -164,8 +177,11 @@ private fun RowScope.KeyCap(
awaitEachGesture {
awaitFirstDown().consume()
down = true; onDown()
waitForUpOrCancellation()?.consume()
down = false; onUp()
try {
waitForUpOrCancellation()?.consume()
} finally {
down = false; onUp()
}
}
}
.onPreviewKeyEvent { e ->
@@ -0,0 +1,38 @@
package com.droiddeck.launcher.ui
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.input.PC_KEY_HIDDEN_GROUPS
import com.droiddeck.launcher.session.SessionPrefs
internal object PcKeyboardPrefs {
var size by mutableStateOf(SessionPrefs.PC_KEYBOARD_SIZE_DEFAULT)
private set
var opacity by mutableStateOf(SessionPrefs.PC_KEYBOARD_OPACITY_DEFAULT)
private set
var hiddenKeys by mutableStateOf(emptySet<String>())
private set
fun load(context: Context) {
size = SessionPrefs.pcKeyboardSize(context)
opacity = SessionPrefs.pcKeyboardOpacity(context)
hiddenKeys = SessionPrefs.pcKeyboardHiddenKeys(context).filter { it in PC_KEY_HIDDEN_GROUPS }.toSet()
}
fun setSize(context: Context, percent: Int) {
size = percent
SessionPrefs.setPcKeyboardSize(context, percent)
}
fun setOpacity(context: Context, percent: Int) {
opacity = percent
SessionPrefs.setPcKeyboardOpacity(context, percent)
}
fun toggleHiddenKey(context: Context, group: String, on: Boolean) {
hiddenKeys = if (on) hiddenKeys + group else hiddenKeys - group
SessionPrefs.setPcKeyboardHiddenKeys(context, hiddenKeys)
}
}
@@ -58,6 +58,7 @@ class SecondScreenPresentation(
private val onMenu: (() -> Unit)? = null,
private val menu: (@androidx.compose.runtime.Composable () -> Unit)? = null,
private val dashboard: (@androidx.compose.runtime.Composable () -> Unit)? = null,
private val onSwap: (() -> Unit)? = null,
) : Presentation(sessionActivity, display) {
private val frame = FrameLayout(context)
private var menuView: androidx.compose.ui.platform.ComposeView? = null
@@ -246,7 +247,7 @@ class SecondScreenPresentation(
SecondScreenMode.DESKTOP -> {
ownComposeViews()
root.addView(BottomDesktopPanel(context, onClose, onMenu,
(onSteamMenu to onQam).takeIf { SessionState.mode == SessionService.MODE_STEAM }), weightParams())
(onSteamMenu to onQam).takeIf { SessionState.mode == SessionService.MODE_STEAM }, onSwap), weightParams())
}
SecondScreenMode.NONE -> Unit
}
@@ -154,6 +154,7 @@ import com.droiddeck.launcher.gpu.SteamVr
import com.droiddeck.launcher.gpu.ScreenEffects
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.input.PC_KEY_GROUP_IDS
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_BEHAVIOR_CLICK
@@ -245,6 +246,9 @@ class DrawerActions(
val textureAnisotropy: Int? = 0,
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
val secondScreenMode: SecondScreenMode,
val gameOnBottom: Boolean = false,
val gameSwapAvailable: Boolean = false,
val onGameOnBottom: (Boolean) -> Unit = {},
val dashboardAvailable: Boolean = false,
val desktopAvailable: Boolean = false,
val secondScreenDisplays: List<SecondScreenDisplay>,
@@ -680,6 +684,28 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
host.open = null; a.onKeyboard()
}
}
val keyboardContext = LocalContext.current
remember { PcKeyboardPrefs.load(keyboardContext) }
SliderRow(
stringResource(R.string.pckb_size), stringResource(R.string.pckb_size_hint),
PcKeyboardPrefs.size, SessionPrefs.PC_KEYBOARD_SIZE_RANGE, step = 1,
format = { "$it%" }, modifier = focus.track(page, "pckb-size"),
onChange = { PcKeyboardPrefs.setSize(keyboardContext, it) })
SliderRow(
stringResource(R.string.pckb_opacity), stringResource(R.string.pckb_opacity_hint),
PcKeyboardPrefs.opacity, SessionPrefs.PC_KEYBOARD_OPACITY_RANGE, step = 5,
format = { "$it%" }, modifier = focus.track(page, "pckb-opacity"),
onChange = { PcKeyboardPrefs.setOpacity(keyboardContext, it) })
MultiRow(
host, "pckb-hidden", stringResource(R.string.pckb_hidden_keys),
stringResource(R.string.pckb_hidden_keys_hint),
listOf(
0 to stringResource(R.string.pckb_group_function),
1 to stringResource(R.string.pckb_group_nav),
2 to stringResource(R.string.pckb_group_arrows),
),
PC_KEY_GROUP_IDS.filterValues { it in PcKeyboardPrefs.hiddenKeys }.keys,
onToggle = { id, on -> PcKeyboardPrefs.toggleHiddenKey(keyboardContext, PC_KEY_GROUP_IDS.getValue(id), on) })
}
}
SessionDrawerPage.SECOND_SCREEN -> {
@@ -1176,6 +1202,11 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String)
a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,
chipModifier = track("second-screen-display"), onPick = a.onSecondScreenDisplay)
}
if (a.gameSwapAvailable || a.gameOnBottom) SettingsGroup(stringResource(R.string.swap_game_screen_group)) {
ChoiceRow(host, "game-screen", stringResource(R.string.swap_game_screen), null,
listOf(false to stringResource(R.string.swap_game_screen_top), true to stringResource(R.string.swap_game_screen_bottom)),
a.gameOnBottom, chipModifier = track("game-screen"), onPick = a.onGameOnBottom)
}
}
@Composable
@@ -61,11 +61,11 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.hud.DroidDeckMark
import com.droiddeck.launcher.hud.FrameStats
import com.droiddeck.launcher.hud.HudMetrics
import com.droiddeck.launcher.session.StatsHud
import java.io.File
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
@@ -164,10 +164,6 @@ private fun HudPanel(clock: String, right: String?, dim: Boolean, accent: Color,
val divider = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = argb(if (dim) 38 else 90, a) }
val blur = BlurMaskFilter(4.dp.toPx(), BlurMaskFilter.Blur.NORMAL)
val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = stroke; color = argb(if (dim) 90 else 255, a) }
val markH = min(h, w) * 0.55f
val markX = w - DroidDeckMark.widthFor(markH) - 16.dp.toPx()
val markBody = android.graphics.Color.argb(if (dim) 9 else 20, 255, 255, 255)
val markOrb = argb(if (dim) 9 else 20, a)
onDrawBehind {
drawIntoCanvas { canvas ->
val c = canvas.nativeCanvas
@@ -176,7 +172,6 @@ private fun HudPanel(clock: String, right: String?, dim: Boolean, accent: Color,
c.clipPath(body)
c.drawRect(0f, 0f, w, headerPx + 1f, band)
c.drawRect(0f, headerPx, w, headerPx + max(1f, density), divider)
DroidDeckMark.draw(c, markX, (h - markH) / 2f, markH, markBody, markOrb)
c.restore()
for (pass in 0..2) {
line.maskFilter = if (pass < 2) blur else null
@@ -189,8 +184,7 @@ private fun HudPanel(clock: String, right: String?, dim: Boolean, accent: Color,
.padding(start = 24.dp, end = 34.dp, bottom = 14.dp),
) {
Row(Modifier.fillMaxWidth().height(HEADER), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
DroidDeckLogo(16.dp, body = headerInk, orb = if (dim) accent.copy(alpha = 0.5f) else accent)
Text("DroidDeck", fontSize = 14.sp, fontWeight = FontWeight.Bold, color = headerInk, maxLines = 1)
Wordmark(14.dp, ink = headerInk, ball = if (dim) accent.copy(alpha = 0.5f) else accent)
if (clock.isNotEmpty()) {
Text("·", fontSize = 13.sp, fontFamily = Mono, color = HudInk.sep)
Text(clock, fontSize = 13.sp, fontFamily = Mono, fontWeight = FontWeight.Bold, color = HudInk.dim, maxLines = 1)
@@ -271,13 +265,18 @@ private fun lowsText(d: HudData, size: TextUnit, accent: Color, deep: Boolean =
}
}
private val GRAPH_MIN_GAP = 3.dp
@Composable
private fun Graph(values: List<Float>, lo: Float, hi: Float, color: Color, modifier: Modifier) {
Canvas(modifier) {
if (values.size < 2 || hi <= lo) return@Canvas
val stride = ceil(GRAPH_MIN_GAP.toPx() * (values.size - 1) / size.width).toInt().coerceAtLeast(1)
val points = if (stride == 1) values else values.chunked(stride) { it.average().toFloat() }
if (points.size < 2) return@Canvas
val path = Path()
values.forEachIndexed { i, v ->
val x = i / (values.size - 1f) * size.width
points.forEachIndexed { i, v ->
val x = i / (points.size - 1f) * size.width
val y = size.height - ((v - lo) / (hi - lo)).coerceIn(0f, 1f) * size.height
if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
}
@@ -111,8 +111,7 @@ private fun LogoBadge(size: Dp) {
private fun LogoHeader(clock: String, game: String?) {
val colors = MaterialTheme.colorScheme
Row(Modifier.fillMaxWidth().padding(horizontal = 2.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
DroidDeckLogo(16.dp)
Text("DroidDeck", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
Wordmark(14.dp, ink = colors.onBackground)
Text(game.orEmpty(), fontSize = 13.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, textAlign = TextAlign.Center,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
if (clock.isNotEmpty()) Text(clock, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
@@ -8,6 +8,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.vector.PathParser
@@ -16,22 +17,21 @@ import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.hud.WordmarkArt
@Composable
internal fun Wordmark(height: Dp, modifier: Modifier = Modifier) {
val ink = MaterialTheme.colorScheme.onBackground
val ball = LocalPalette.current.signal
internal fun Wordmark(height: Dp, modifier: Modifier = Modifier, ink: Color = MaterialTheme.colorScheme.onBackground, ball: Color = LocalPalette.current.signal) {
val name = stringResource(R.string.app_name)
val letters = remember { PathParser().parsePathString(LETTERS).toPath() }
val leftHalf = remember { PathParser().parsePathString(LEFT_HALF).toPath() }
val rightHalf = remember { PathParser().parsePathString(RIGHT_HALF).toPath() }
Canvas(modifier.height(height).width(height * (BOX_W / BOX_H)).semantics { contentDescription = name }) {
val k = size.height / BOX_H
val letters = remember { PathParser().parsePathString(WordmarkArt.LETTERS).toPath() }
val leftHalf = remember { PathParser().parsePathString(WordmarkArt.LEFT_HALF).toPath() }
val rightHalf = remember { PathParser().parsePathString(WordmarkArt.RIGHT_HALF).toPath() }
Canvas(modifier.height(height).width(height * (WordmarkArt.BOX_W / WordmarkArt.BOX_H)).semantics { contentDescription = name }) {
val k = size.height / WordmarkArt.BOX_H
scale(k, k, Offset.Zero) {
translate(-BOX_X, -BOX_Y) {
translate(-WordmarkArt.BOX_X, -WordmarkArt.BOX_Y) {
drawPath(letters, ink)
translate(239.135f, 123.36f) {
scale(MARK_SCALE, MARK_SCALE, Offset.Zero) {
scale(WordmarkArt.MARK_SCALE, WordmarkArt.MARK_SCALE, Offset.Zero) {
translate(31.98f, 0f) {
drawPath(leftHalf, ink)
drawPath(rightHalf, ink)
@@ -43,22 +43,3 @@ internal fun Wordmark(height: Dp, modifier: Modifier = Modifier) {
}
}
}
private const val BOX_X = 239.135f
private const val BOX_Y = 120.02f
private const val BOX_W = 1040.7f - 239.135f
private const val BOX_H = 243.2f - 120.02f
private const val MARK_SCALE = 0.527445f
private const val LEFT_HALF = "M-31.98 0H56.055V40.489A71.81 71.81 0 0 0 56.055 183.231V223.72H-31.98Z"
private const val RIGHT_HALF = "M71.885 0.28A111.86 111.86 0 0 1 71.885 223.44V183.234A71.81 71.81 0 0 0 71.885 40.486Z"
private const val LETTERS =
"M361.45 241.36V160.13H387.02V241.36ZM387.02 196.73 376.32 188.38Q379.5 174.17 387.02 166.31Q394.54 158.46 407.91 158.46Q413.76 158.46 418.19 160.21Q422.62 161.97 425.96 165.65L410.75 184.87Q409.08 183.03 406.57 182.03Q404.07 181.02 400.89 181.02Q394.54 181.02 390.78 184.95Q387.02 188.88 387.02 196.73" +
"ZM467.91 243.2Q455.38 243.2 445.27 237.6Q435.15 232 429.3 222.31Q423.45 212.61 423.45 200.58Q423.45 188.54 429.3 179.02Q435.15 169.49 445.18 163.89Q455.21 158.29 467.91 158.29Q480.62 158.29 490.64 163.81Q500.67 169.32 506.52 178.93Q512.37 188.54 512.37 200.58Q512.37 212.61 506.52 222.31Q500.67 232 490.64 237.6Q480.62 243.2 467.91 243.2" +
"ZM467.91 219.97Q473.43 219.97 477.61 217.54Q481.79 215.12 484.04 210.69Q486.3 206.26 486.3 200.58Q486.3 194.9 483.96 190.63Q481.62 186.37 477.52 183.95Q473.43 181.52 467.91 181.52Q462.56 181.52 458.39 183.95Q454.21 186.37 451.87 190.72Q449.53 195.06 449.53 200.75Q449.53 206.26 451.87 210.69Q454.21 215.12 458.39 217.54Q462.56 219.97 467.91 219.97" +
"ZM523.4 241.36V160.13H548.98V241.36ZM536.27 148.93Q530.26 148.93 526.33 144.84Q522.4 140.74 522.4 134.89Q522.4 128.88 526.33 124.86Q530.26 120.85 536.27 120.85Q542.29 120.85 546.13 124.86Q549.98 128.88 549.98 134.89Q549.98 140.74 546.13 144.84Q542.29 148.93 536.27 148.93ZM599.95 243.03Q588.42 243.03 579.48 237.52Q570.54 232 565.44 222.47Q560.34 212.95 560.34 200.75Q560.34 188.54 565.44 179.02Q570.54 169.49 579.48 163.97Q588.42 158.46 599.95 158.46Q608.31 158.46 615.08 161.63Q621.85 164.81 626.28 170.41Q630.71 176.01 631.21 183.2V217.46Q630.71 224.65 626.36 230.41Q622.02 236.18 615.16 239.61Q608.31 243.03 599.95 243.03" +
"ZM604.47 219.97Q609.98 219.97 613.99 217.54Q618 215.12 620.34 210.77Q622.68 206.43 622.68 200.75Q622.68 195.06 620.43 190.8Q618.17 186.54 614.08 184.03Q609.98 181.52 604.63 181.52Q599.28 181.52 595.19 184.03Q591.09 186.54 588.67 190.88Q586.25 195.23 586.25 200.75Q586.25 206.26 588.59 210.61Q590.93 214.95 595.11 217.46Q599.28 219.97 604.47 219.97" +
"ZM646.75 241.36H621.68V219.46L625.53 199.74L621.18 180.02V120.02H646.75ZM683.19 241.36V218.29H712.44Q723.13 218.29 731.16 214.03Q739.18 209.77 743.53 201.58Q747.87 193.39 747.87 182.19Q747.87 170.99 743.44 162.97Q739.01 154.95 731.07 150.6Q723.13 146.26 712.44 146.26H682.35V123.36H712.77Q726.14 123.36 737.42 127.62Q748.71 131.88 757.15 139.82Q765.59 147.76 770.18 158.54Q774.78 169.32 774.78 182.36Q774.78 195.23 770.18 206.09Q765.59 216.96 757.23 224.81Q748.87 232.67 737.59 237.01Q726.31 241.36 713.11 241.36" +
"ZM665.47 241.36V123.36H691.71V241.36ZM827.6 243.2Q814.39 243.2 804.11 237.77Q793.83 232.33 787.98 222.64Q782.13 212.95 782.13 200.75Q782.13 188.54 787.9 178.93Q793.67 169.32 803.53 163.81Q813.39 158.29 825.76 158.29Q837.79 158.29 846.98 163.47Q856.18 168.65 861.44 177.85Q866.71 187.04 866.71 198.91Q866.71 201.08 866.46 203.5Q866.21 205.93 865.54 209.1L795.51 209.27V191.72L854.67 191.55L843.64 198.91Q843.47 191.89 841.47 187.29Q839.46 182.69 835.54 180.27Q831.61 177.85 825.92 177.85Q819.91 177.85 815.48 180.61Q811.05 183.36 808.63 188.38Q806.2 193.39 806.2 200.58Q806.2 207.77 808.79 212.86Q811.38 217.96 816.15 220.72Q820.91 223.48 827.43 223.48Q833.45 223.48 838.29 221.39Q843.14 219.3 846.82 215.12L860.86 229.16Q854.84 236.18 846.32 239.69Q837.79 243.2 827.6 243.2" +
"ZM916.68 243.2Q904.15 243.2 893.95 237.68Q883.75 232.17 877.9 222.47Q872.05 212.78 872.05 200.75Q872.05 188.54 877.99 178.93Q883.92 169.32 894.12 163.81Q904.31 158.29 917.02 158.29Q926.54 158.29 934.48 161.55Q942.42 164.81 948.6 171.33L932.22 187.71Q929.38 184.53 925.62 183.03Q921.86 181.52 917.02 181.52Q911.5 181.52 907.24 183.95Q902.98 186.37 900.55 190.63Q898.13 194.9 898.13 200.58Q898.13 206.26 900.55 210.61Q902.98 214.95 907.32 217.46Q911.67 219.97 917.02 219.97Q922.03 219.97 925.96 218.21Q929.88 216.46 932.73 213.28L948.94 229.66Q942.59 236.35 934.56 239.77Q926.54 243.2 916.68 243.2" +
"ZM1010.61 241.36 982.2 199.24 1010.45 160.13H1039.03L1004.93 204.09L1005.77 193.56L1040.7 241.36ZM958.63 241.36V120.02H984.21V241.36Z"
@@ -20,12 +20,15 @@ class BottomDesktopCompositorService : Service() {
private var client: Messenger? = null
/** Echoed in every reply, so the session process can tell replies to an earlier attach apart. */
@Volatile private var attachTag = 0
private var outputWidth = 0
private var outputHeight = 0
private val handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
when (msg.what) {
MSG_ATTACH -> attach(msg)
MSG_DETACH -> CompositorHost.detach(null)
MSG_RESIZE -> resize(msg.arg1, msg.arg2)
MSG_TOUCH -> WaylandCompositor.nativeSendTouch(msg.arg1 and 0xff, msg.arg1 shr 8,
msg.arg2 ushr 16, msg.arg2 and 0xffff)
MSG_KEY -> WaylandCompositor.nativeSendKey(msg.arg1, msg.arg2)
@@ -75,15 +78,26 @@ class BottomDesktopCompositorService : Service() {
}
val turnip = com.droiddeck.launcher.gpu.TurnipDriver(this)
val driverId = if (CompositorHost.isStarted) null else turnip.install()
val resized = CompositorHost.isStarted && (width != outputWidth || height != outputHeight)
val started = CompositorHost.startOrAttach(
this, surface, runtimeDir.path, driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
applicationInfo.nativeLibraryDir,
width, height, data.getFloat(KEY_REFRESH, 60f), 0,
)
outputWidth = width
outputHeight = height
if (resized) WaylandCompositor.nativeResizeOutput(width, height)
Log.i(TAG, (if (started) "compositor started" else "compositor attached") + " at ${width}x$height in ${runtimeDir.path}")
reply(MSG_ATTACHED)
}
private fun resize(width: Int, height: Int) {
if (width <= 0 || height <= 0 || !CompositorHost.isStarted || (width == outputWidth && height == outputHeight)) return
outputWidth = width
outputHeight = height
WaylandCompositor.nativeResizeOutput(width, height)
}
private fun reply(what: Int) {
val target = client ?: return
runCatching { target.send(Message.obtain(null, what, attachTag, 0)) }
@@ -102,6 +116,7 @@ class BottomDesktopCompositorService : Service() {
const val MSG_POINTER = 8
const val MSG_SCENE = 9
const val MSG_CURSOR = 10
const val MSG_RESIZE = 11
const val MSG_ATTACHED = 101
const val MSG_FIRST_FRAME = 102
const val KEY_RUNTIME_DIR = "runtimeDir"