diff --git a/README.md b/README.md index 7fc0b80114..2e81870b62 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05. - mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). -- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT). FEX's code disk cache was checked in its source. +- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. - x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence. - x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes. - `WriteProcessMemory` hooks fall back to `/proc//mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11. @@ -98,6 +98,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. - The EA store follows the EA app's protocols as documented by [ArmchairDevelopers](https://github.com/ArmchairDevelopers)' [Maxima](https://github.com/ArmchairDevelopers/Maxima) (GPL-3.0): sign-in, the GraphQL queries (included verbatim, since EA matches them by hash), build archives, online activation licences and the LSX game endpoint. The code is DroidDeck's own. - Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader. +- The Rockstar launcher service looks for launcher pipe names in the executables beside the game, since [CitizenFX](https://github.com/citizenfx/fivem)'s `ros-patches-five` shows GTA V opening `GTAVLauncher_Pipe` and [@pingod](https://github.com/pingod)'s [rdr2-linux-launcher](https://github.com/pingod/rdr2-linux-launcher) notes that Rockstar's protected executables resolve such strings only at run time. Read without taking code. - World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used. - The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. [CurseForge](https://www.curseforge.com/wow) opens in the user's browser, with no API and no key. - The Xbox store runs [@domsvoboda](https://github.com/domsvoboda)'s [nexus-backend](https://github.com/domsvoboda/nexus-backend) 0.2.15 (GPL-3.0, a fork of [Xodus](https://github.com/xodus-gaming/xodus)), and Xbox games load the Windows modules of his [nexus-runtime](https://github.com/domsvoboda/nexus-runtime) (LGPL-2.1-or-later), including the C++ [nexus-xgameruntime](https://github.com/domsvoboda/nexus-xgameruntime) and `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, as nexus-backend's Store license path (commit `27c335e`) does. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT). diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index f8e0fb414b..39ae906175 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -191,6 +191,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var unfoldedPanel by mutableStateOf(null) private var unfoldedColumn: android.widget.LinearLayout? = null private var unfoldedDeckSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null + private var swappedInputSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null private var unfoldedDeckPanel by mutableStateOf(null) private var deckPanelLayouts: Map = emptyMap() private lateinit var sessionRoot: FrameLayout @@ -200,6 +201,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde @Volatile private var inputUsesLocalActions = false private var inputUsesPointer = false private var inputProfile = InputProfile.defaults(InputProfile.GAME) + private var stockInputProfile = InputProfile.defaults(InputProfile.GAME) private val inputMotion = InputMotion { inputRouter } private val heldKeys = HeldInput { code, down -> WaylandCompositor.nativeSendKey(code, if (down) 1 else 0) } private val heldButtons = HeldInput(::sendSceneButton) @@ -539,6 +541,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var lastMouseY = Float.NaN private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK) private var pcKeyboardOpen by mutableStateOf(false) + private var fieldKeyboardOnPrimary = false + private var pendingFieldKeyboard = false + private var fieldKeyboardImeShown = false private var achievementsInFront by mutableStateOf(null) private var achievementsOpen by mutableStateOf(false) private var hudOn by mutableStateOf(true) @@ -656,11 +661,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onDisplayAdded(displayId: Int) { notifyActivityDisplayStateChanged(displayId) refreshSecondScreenDisplays() + updateBottomGame() } override fun onDisplayRemoved(displayId: Int) { if (refreshActivityDisplayId() && started) { SessionService.setActivityDisplay(this@SessionActivity, sessionActivityDisplayId) } + updateBottomGame() refreshSecondScreenDisplays() } override fun onDisplayChanged(displayId: Int) { @@ -872,10 +879,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde root.addView(controls) } keyboard = KeyboardHost(this).also { host -> - host.onImeChanged = { updateDesktopKeyboardButton() } + host.onImeChanged = ::onPrimaryImeChanged root.addView(host) } - desktopKeyboardButton = com.droiddeck.launcher.input.DesktopKeyboardButton(this) { keyboard?.show() } + desktopKeyboardButton = com.droiddeck.launcher.input.DesktopKeyboardButton(this) { showPrimaryKeyboard() } .also { root.addView(it) } touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener) directTouchHold = DirectTouchHold(PointerGestures.slop(this), pointerListener, directTouchSink) @@ -893,6 +900,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde drawnRect()?.let { forwardTouch(event, it) } } override fun rightClick(x: Float, y: Float) { + if (!screenTapsClick) return pointerListener.onLongPress() pointerListener.onButton(PointerGestures.BTN_RIGHT, true, x, y) surfaceView.postDelayed({ pointerListener.onButton(PointerGestures.BTN_RIGHT, false, x, y) }, 50L) @@ -1090,6 +1098,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (AgentGuest.keyboardDismissals != keyboardDismissalsSeen[0]) { keyboardDismissalsSeen[0] = AgentGuest.keyboardDismissals secondScreenPresentation?.closeFieldKeyboard() + dismissFieldKeyboard() } } androidx.compose.runtime.LaunchedEffect(picturePosition, integerScaling, SessionState.running, pipUi, cardboard.enabled) { applyGameAlignment() } @@ -1312,7 +1321,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } if (pcKeyboardOpen) com.droiddeck.launcher.ui.PcKeyboard( sendKey = { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down, 32) }, - onAndroidKeyboard = { pcKeyboardOpen = false; keyboard?.toggle() }, + onAndroidKeyboard = { pcKeyboardOpen = false; togglePrimaryKeyboard() }, onClose = { pcKeyboardOpen = false }, ) if (!drawerDocked) SessionMenu( @@ -1436,6 +1445,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde secondScreenNone = !bottomOutputActive && !dockDrawer(), gameOnBottom = bottomOutputActive, gameSwapAvailable = bottomSwapAvailable, + gameSwapBuiltIn = !::displayManager.isInitialized || displayManager.getDisplay(selectedSecondScreenDisplay) + ?.let(com.droiddeck.launcher.input.DualScreen::builtIn) ?: true, onGameOnBottom = { on -> drawerOpen = false; putGameOnBottom(on) }, dashboardAvailable = bottomPages().isNotEmpty(), desktopAvailable = com.droiddeck.launcher.session.BottomDesktop.available(), @@ -1629,7 +1640,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde pickLossless.launch(InAppFilePicker.buildIntent( this@SessionActivity, listOf("dll"), getString(R.string.lsfg_pick_title))) }, - onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; keyboard?.toggle() }, + onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; togglePrimaryKeyboard() }, onHardwareKeyboard = ::togglePcKeyboard, wowChatShown = com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram), wowChat = wowChat.remembered, @@ -1860,7 +1871,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val all = com.droiddeck.launcher.input.VrControllers.Emulate.entries com.droiddeck.launcher.input.VrControllers.setEmulate(this, all[(pads.emulate.ordinal + 1) % all.size]) }) else null, - onKeyboard = { keyboard?.toggle() }, + onKeyboard = { togglePrimaryKeyboard() }, onSessionMenu = { drawerOpen = true }, onStopSteamVr = if (vr) ({ steamVrAction("stop") }) else null, brightness = glasses.brightness, @@ -1901,12 +1912,44 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun togglePcKeyboard() { drawerOpen = false - keyboard?.hide() + hidePrimaryKeyboard() onScreenControls?.releaseAll() bottomInputControls?.releaseAll() pcKeyboardOpen = !pcKeyboardOpen } + private fun showPrimaryKeyboard() { + pendingFieldKeyboard = false + fieldKeyboardOnPrimary = false + keyboard?.show() + } + + private fun togglePrimaryKeyboard() { + pendingFieldKeyboard = false + fieldKeyboardOnPrimary = false + keyboard?.toggle() + } + + private fun hidePrimaryKeyboard() { + pendingFieldKeyboard = false + fieldKeyboardOnPrimary = false + keyboard?.hide() + } + + private fun onPrimaryImeChanged(visible: Boolean) { + if (visible) fieldKeyboardImeShown = true + else if (fieldKeyboardImeShown) { + fieldKeyboardImeShown = false + fieldKeyboardOnPrimary = false + } + updateDesktopKeyboardButton() + } + + private fun dismissFieldKeyboard() { + pendingFieldKeyboard = false + if (fieldKeyboardOnPrimary) hidePrimaryKeyboard() + } + private fun updateControllerPrefs(change: () -> Unit) { change() controllerSettings = ControllerPrefs.read(this) @@ -3657,7 +3700,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return false return try { val presentation = secondScreenPresentation ?: secondScreenPresentation(target).also { - selectedSecondScreenDisplay = target.displayId secondScreenPresentation = it } if (!presentation.isShowing) presentation.show() @@ -4016,16 +4058,23 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val candidates = SecondScreenDisplays.available(displayManager, primaryId) .filter { glassesScreen == null || it.id != glasses.displayId } val oldIds = secondScreenDisplays.map { it.id }.toSet() + val oldSelectedDisplay = selectedSecondScreenDisplay secondScreenDisplays = candidates reconcileDock(primaryId) - bottomSwapAvailable = bottomGame != null || bottomGameDisplay() != null val newIds = candidates.map { it.id }.toSet() if (secondScreenMode != SecondScreenMode.NONE && oldIds.isNotEmpty() && selectedSecondScreenDisplay !in newIds) { + bottomSwapAvailable = bottomGame != null closeSecondScreen(reset = true) SessionState.secondScreenAutoOpened = false return } - if (selectedSecondScreenDisplay !in newIds) selectedSecondScreenDisplay = candidates.firstOrNull()?.id ?: -1 + selectedSecondScreenDisplay = SecondScreenDisplays.selection(selectedSecondScreenDisplay, candidates.map { it.id }, gameOnBottom) { + SessionState.secondScreenDisplay = it + } + if (selectedSecondScreenDisplay != oldSelectedDisplay) { + updateBottomGame() + } + bottomSwapAvailable = bottomGame != null || bottomGameDisplay() != null if (secondScreenMode != SecondScreenMode.NONE && candidates.isEmpty()) { closeSecondScreen(reset = true) SessionState.secondScreenAutoOpened = false @@ -4047,12 +4096,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun openDualScreenControls() { if (SessionState.secondScreenAutoOpened || secondScreenMode != SecondScreenMode.NONE || pipUi) return + if (gameOnBottom && selectedSecondScreenDisplay >= 0 && secondScreenDisplays.none { it.id == selectedSecondScreenDisplay }) return if (!SessionPrefs.dualScreenSessionControls(this)) return val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return if (secondScreenDisplays.none { it.id == target.displayId }) return + val gameDisplay = bottomGame?.display?.displayId + ?: if (SessionState.gameOnBottom) bottomGameDisplay()?.displayId else null SessionState.secondScreenAutoOpened = true - selectedSecondScreenDisplay = target.displayId - selectSecondScreenMode(openingPanel()) + if (gameDisplay != null && gameDisplay != target.displayId && secondScreenDisplays.any { it.id == gameDisplay }) { + panelMode(openingPanel()) + } else { + val selectionChanged = selectedSecondScreenDisplay != target.displayId + selectedSecondScreenDisplay = target.displayId + SessionState.secondScreenDisplay = target.displayId + if (selectionChanged) updateBottomGame() + selectSecondScreenMode(openingPanel()) + } automaticPanel = secondScreenMode != SecondScreenMode.NONE dualControlsProvisional = ::loading.isInitialized && loading.visible } @@ -4078,6 +4137,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (secondScreenDisplays.none { it.id == displayId }) return selectedSecondScreenDisplay = displayId SessionState.secondScreenDisplay = displayId + updateBottomGame() if (secondScreenMode != SecondScreenMode.NONE) showSecondScreen(secondScreenMode) } @@ -4096,6 +4156,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde return } if (selectedSecondScreenDisplay !in secondScreenDisplays.map { it.id }) { + if (gameOnBottom && selectedSecondScreenDisplay >= 0) { + panelMode(mode) + return + } selectedSecondScreenDisplay = secondScreenDisplays.first().id } showSecondScreen(mode) @@ -4174,7 +4238,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde ) } }, - onSwap = if (bottomSwapAvailable && com.droiddeck.launcher.input.DualScreen.builtIn(target)) ({ putGameOnBottom(true) }) else null, + onSwap = if (bottomSwapAvailable) ({ putGameOnBottom(true) }) else null, onDeckPanel = ::selectDeckPanel, dashboard = if (bottomPages().isEmpty()) null else ({ DroidDeckTheme { @@ -4278,6 +4342,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val library = com.droiddeck.launcher.input.InputLibraries.read(this) val desktop = loadingMode() == SessionService.MODE_DESKTOP inputProfile = library.compileActive(desktop, secondScreenMode.panel(this)) + stockInputProfile = library.compileStock(desktop, secondScreenMode.panel(this)) primaryInputLayout = library.activeLayout(desktop, InputRole.PRIMARY) adaptiveSticks = primaryInputLayout?.adaptiveSticks quickButtons = primaryInputLayout?.takeIf { it.editable }?.let { l -> l.quickButtons.associateWith { it !in l.style.hidden } }.orEmpty() @@ -4417,6 +4482,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (!started) return null if (secondScreenPresentation?.showsKeyboard != true && dockDrawer()) { val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return null + if (gameOnBottom && selectedSecondScreenDisplay != target.displayId) return null if (drawerOpen || drawerPinned) drawerOpen = false typingReturnMode = secondScreenMode selectedSecondScreenDisplay = target.displayId @@ -4426,16 +4492,37 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun openBottomKeyboard() { - val presentation = bottomKeyboardPresentation() ?: return + val presentation = bottomKeyboardPresentation() + if (presentation == null) { + if (keyboardBelongsOnPrimary()) { + pendingFieldKeyboard = true + retryFieldKeyboard(hasWindowFocus()) + } + return + } + pendingFieldKeyboard = false + if (fieldKeyboardOnPrimary) hidePrimaryKeyboard() presentation.requestKeyboard(forField = true) com.droiddeck.launcher.ui.SessionTyping.focusDisplay(this, presentation.display.displayId) } + private fun keyboardBelongsOnPrimary() = SecondScreenDisplays.keyboardOnPrimary(gameOnBottom, selectedSecondScreenDisplay, + secondScreenDisplays.map { it.id }, taken = com.droiddeck.launcher.input.DualScreen::taken) + + private fun retryFieldKeyboard(hasFocus: Boolean) { + if (!pendingFieldKeyboard || !hasFocus || !resumed || pipUi) return + pendingFieldKeyboard = false + if (!keyboardBelongsOnPrimary()) return + fieldKeyboardOnPrimary = true + fieldKeyboardImeShown = keyboard?.hideMeansDismissal == true + keyboard?.show() + } + private fun onGameTextField(focused: Boolean) { if (!focused || !com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram)) wowChat.chatClosed() else if (resumed && !pipUi && !pcKeyboardOpen && resources.configuration.hardKeyboardHidden != android.content.res.Configuration.HARDKEYBOARDHIDDEN_NO) { - keyboard?.takeIf { it.shown }?.hide() + hidePrimaryKeyboard() wowChat.chatOpened() } } @@ -4522,9 +4609,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun updateKeyboardRoute() { - AgentGuest.routeKeyboard(this, SessionState.mode == SessionService.MODE_STEAM && - (secondScreenPresentation?.showsKeyboard == true || dockDrawer()) && - SessionPrefs.androidTextFieldKeyboard(this)) + AgentGuest.routeKeyboard(this, SecondScreenDisplays.routeKeyboard( + SessionState.mode == SessionService.MODE_STEAM, + SessionPrefs.androidTextFieldKeyboard(this), + secondScreenPresentation?.showsKeyboard == true, + dockDrawer(), + SecondScreenDisplays.keyboardOnPrimary(gameOnBottom, selectedSecondScreenDisplay, + secondScreenDisplays.map { it.id }, resumed && !pipUi, com.droiddeck.launcher.input.DualScreen::taken))) } private fun dropDockedDrawer() { @@ -4735,6 +4826,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var lockedSwipeY = 0f private var dismissTouch = false private var sessionTouchDown = false + private var screenTapsClick = true + + private fun onScreenMouseButtonShown(): Boolean = listOfNotNull( + onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, unfoldedDeckSurface, + secondScreenPresentation?.controlsView, swappedInputSurface, + ).any { it.isShown && inputProfile.showsMouseButton(it.inputRole, it.shownElements, stockInputProfile) } override fun onTouchEvent(event: MotionEvent): Boolean { val pen = PenStream.penIndex(event) @@ -4767,6 +4864,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } val snapshot = fingerTouchSnapshot(uiBlocking) val route = com.droiddeck.launcher.input.TouchRouter.decide(snapshot) + if (event.actionMasked == MotionEvent.ACTION_DOWN) { + screenTapsClick = !onScreenMouseButtonShown() + if (::touchpad.isInitialized) touchpad.clicks = screenTapsClick + if (::scrollTouch.isInitialized) scrollTouch.clicks = screenTapsClick + } if (route != touchRoute) { Log.i(TAG, "touch route $touchRoute -> $route (mode=$routedTouchMode steamUi=${SessionState.steamUi} scrollLayer=$scrollTouchGesture)") touchRoute = route @@ -4916,6 +5018,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) ignoreGameTouch = false return true } + // With an on-screen mouse button the press comes from the button, so the pointer has to be there before + // the two-finger gesture buffer holds the touch-down. + if (SessionState.mode == SessionService.MODE_DESKTOP && !screenTapsClick && !pointerLocked && + event.actionMasked == MotionEvent.ACTION_DOWN) movePointer(event.x, event.y) if (SessionState.mode == SessionService.MODE_DESKTOP && twoFingerGestures.onTouch(event)) return true return forwardTouch(event, rect) } @@ -4950,7 +5056,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } } - directTouchHold.onTouch(event) + if (screenTapsClick) directTouchHold.onTouch(event) + else if (!pointerLocked && (event.actionMasked == MotionEvent.ACTION_DOWN || event.actionMasked == MotionEvent.ACTION_MOVE)) + movePointer(event.x, event.y) return true } @@ -5406,6 +5514,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun showPipUi(show: Boolean) { pipUi = show + updateKeyboardRoute() + if (!show) retryFieldKeyboard(hasWindowFocus()) if (show) { if (::hud.isInitialized) hud.setHidden(true) drawerOpen = false @@ -5425,7 +5535,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde guestKeysDown.toList().forEach { sendGuestKey(it, false) } heldKeys.clear() heldButtons.clear() - keyboard?.hide() + hidePrimaryKeyboard() sessionClipboard.stop() padMotion?.stop() cursorVisible = false @@ -5568,6 +5678,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onScreenControls?.reload() controllerSettings = ControllerPrefs.read(this) resumed = true + updateKeyboardRoute() + retryFieldKeyboard(hasWindowFocus()) updateDesktopKeyboardButton() com.droiddeck.launcher.input.HomeButtonShortcuts.attach(this, enabled = { @@ -5641,9 +5753,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (::scrollTouch.isInitialized) scrollTouch.cancel() if (::padMouse.isInitialized) padMouse.reset() resumed = false + updateKeyboardRoute() updatePointerCapture() updatePadMotion() - keyboard?.takeIf { it.shown }?.hide() + val pendingKeyboard = pendingFieldKeyboard + hidePrimaryKeyboard() + pendingFieldKeyboard = pendingKeyboard SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(cardboardPrefListener) SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(screenEffectsProfilePrefListener) ControllerPrefs.prefs(this).unregisterOnSharedPreferenceChangeListener(shortcutPrefListener) @@ -5889,9 +6004,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } 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) } + if (!::displayManager.isInitialized || SessionPrefs.dualScreenSessionMode(this) == com.droiddeck.launcher.input.DualScreen.MODE_OFF) return null + return com.droiddeck.launcher.input.DualScreen.selectedSessionDisplay( + this, displayManager, shownOnDisplayId, selectedSecondScreenDisplay, + ) } private fun putGameOnBottom(on: Boolean) { @@ -6017,7 +6133,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde tabs = tabs, ) val keyboardExtra = com.droiddeck.launcher.ui.BarExtra(getString(R.string.second_show_keyboard), icon = R.drawable.ic_bottom_keyboard) { - keyboard?.toggle() + togglePrimaryKeyboard() } val profileLayout = secondaryInputLayout androidx.compose.foundation.layout.Box( @@ -6045,8 +6161,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde androidx.compose.runtime.key(profileLayout) { androidx.compose.ui.viewinterop.AndroidView( factory = { context -> com.droiddeck.launcher.ui.InputSurfaceView(context, padBridge, profileLayout?.elements.orEmpty(), - surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()) }, + surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()).also { swappedInputSurface = it } }, modifier = Modifier.fillMaxWidth().weight(1f), + onRelease = { if (swappedInputSurface === it) swappedInputSurface = null }, ) } } @@ -6213,6 +6330,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde releaseHeldGuestInput() } if (hasFocus && !pipUi) { + retryFieldKeyboard(true) goFullscreen() refreshClipboard() } diff --git a/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt b/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt index 848fc65701..1d8bf5d682 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt @@ -82,6 +82,12 @@ object DualScreen { fun sessionDisplay(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? = display(context, displayManager, primaryDisplayId, SessionPrefs.dualScreenSessionMode(context)) + fun selectedSessionDisplay(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, selectedDisplayId: Int): Display? = + displayManager.getDisplay(selectedDisplayId)?.takeIf { + SessionPrefs.dualScreenSessionMode(context) != MODE_OFF && it.isValid && it.displayId != primaryDisplayId && + (it.flags and Display.FLAG_PRESENTATION) != 0 && !taken(it.displayId) + } + fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? = when (mode) { MODE_OFF -> null diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt index cc6313dc30..0e5ed4261f 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt @@ -97,6 +97,16 @@ data class InputLibrary( fun compileActive(isDesktop: Boolean, panel: String? = null): InputProfile = compileParts(activeId(isDesktop), InputRole.entries.associateWith { preset(if (it == InputRole.SECONDARY) panelPart(isDesktop, panel).bindings else activePart(isDesktop, it).bindings) }) + fun compileStock(isDesktop: Boolean, panel: String? = null): InputProfile { + val defaults = InputProfile.defaults(profile(activeId(isDesktop)).base) + val stock = InputStockLayouts.presets(InputStockLayouts.layouts()) + return compileParts(defaults.id, InputRole.entries.associateWith { role -> + val part = if (role == InputRole.SECONDARY) panelPart(isDesktop, panel) else activePart(isDesktop, role) + val origin = layouts.firstOrNull { it.id == part.layout }?.origin ?: part.layout + stock.firstOrNull { it.id == part.bindings || (origin != null && it.layoutId == origin) } + ?: SavedInputBindings(part.bindings, "", role == InputRole.PHYSICAL, part.layout, defaults.bindings[role].orEmpty()) + }) + } fun saveSelection(isDesktop: Boolean, name: String, id: String = newInputId()): InputLibrary { val current = profile(activeId(isDesktop)) diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputProfile.kt b/app/src/main/java/com/droiddeck/launcher/input/InputProfile.kt index 2375cf34e8..a122766271 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputProfile.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputProfile.kt @@ -53,6 +53,16 @@ data class InputProfile( fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id) ?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) } + fun showsMouseButton(role: InputRole, shown: List, stock: InputProfile): Boolean = shown.any { element -> + val action = elementAction(role, element.id, element.control).takeIf { + elements[role]?.get(element.id) != stock.elements[role]?.get(element.id) || it != stock.elementAction(role, element.id, element.control) + } + val click = elementClickAction(role, element).takeIf { + clicks[role]?.get(element.id) != stock.clicks[role]?.get(element.id) || it != stock.elementClickAction(role, element) + } + listOfNotNull(action, click).any { it is InputAction.MouseButton && it.validFor(element.control) } + } + companion object { const val GAME = "game" const val DESKTOP = "desktop" diff --git a/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt b/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt index 6656b7697f..5372be6db5 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt @@ -26,6 +26,8 @@ class KeyboardHost( var imeShowing = false private set var onImeChanged: ((Boolean) -> Unit)? = null + val hideMeansDismissal: Boolean + get() = Build.VERSION.SDK_INT < Build.VERSION_CODES.R || (shown && imeShowing) init { isFocusable = false diff --git a/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt index e281a2b741..2a36489e85 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt @@ -176,7 +176,7 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid } - fun elements(): List { + fun elements(previousStickGeometry: Boolean = false): List { fit = fitScale() controls.forEach { it.radius = scaled(it.radiusDp) } placeAuto(width.toFloat(), height.toFloat()) @@ -189,7 +189,7 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid }.map { c -> InputSurfaceElement(requireNotNull(InputControl.fromId(c.id)), (c.cx - c.halfW) / width, (c.cy - c.halfH) / height, 2 * c.halfW / width, 2 * c.halfH / height, floating = settings.adaptiveSticks, hideWhenIdle = c.stick >= 0 && settings.adaptiveSticks, - buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let(::widenStick).bounded() + buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let { if (previousStickGeometry) widenStickPreviously(it) else widenStick(it) }.bounded() }.toMutableList() if (settings.keyboardButton) result += keyboard() return result @@ -315,7 +315,7 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid return e.copy(x = (cx - radius) / width, y = (cy - radius) / height, width = 2 * radius / width, height = 2 * radius / height) } - private fun widenStick(e: InputSurfaceElement): InputSurfaceElement { + private fun widenStickPreviously(e: InputSurfaceElement): InputSurfaceElement { val extra = e.width * (STICK_REACH - 1f) return when (e.control) { InputControl.LS -> (e.x - extra).coerceAtLeast(0f).let { x -> e.copy(x = x, width = e.x + e.width - x) } @@ -323,6 +323,16 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid else -> e } } + + private fun widenStick(e: InputSurfaceElement): InputSurfaceElement { + val extra = e.width * (STICK_REACH - 1f) + val width = e.width + extra + return when (e.control) { + InputControl.LS -> e.copy(x = (e.x - extra).coerceIn(0f, (1f - width).coerceAtLeast(0f)), width = width) + InputControl.RS -> e.copy(x = e.x.coerceIn(0f, (1f - width).coerceAtLeast(0f)), width = width) + else -> e + } + } private companion object { const val MIN_FACE_MM = 9.5f const val FULL_SIZE_HEIGHT_MM = 85f diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt index 4923221fa0..ee3a6560ae 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt @@ -32,6 +32,7 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo var isPinnedOnly = false private set val hasPinned get() = layout?.elements?.any { it.alwaysShown } == true + val inputSurface: com.droiddeck.launcher.ui.InputSurfaceView get() = surface var onTouchMiss: ((MotionEvent) -> Unit)? get() = surface.onTouchMiss set(value) { surface.onTouchMiss = value } diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt index 3935c1a565..9fbb01c7ad 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt @@ -5,6 +5,7 @@ import android.graphics.Rect import kotlin.math.abs import kotlin.math.max import kotlin.math.min +import kotlin.math.roundToInt object OnScreenLayout { data class Dock(val portrait: Boolean, val grips: Boolean, val left: InputControl = InputControl.LS, val right: InputControl = InputControl.RS) { @@ -41,6 +42,14 @@ object OnScreenLayout { return stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } } } + fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List = + elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, Rect()) + + fun editorFrame(layout: SavedInputLayout, displayed: List): List { + val byId = displayed.associateBy { it.id } + return layout.elements.map { byId[it.id] ?: it } + } + fun fit(elements: List, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List { val w = width.toFloat() val h = height.toFloat() @@ -77,8 +86,11 @@ object OnScreenLayout { if (gamepad.any { it.id.startsWith("legacy:") }) { val named = layout.id.removePrefix("migrated.layout.").takeIf { it != layout.id }?.split('x')?.mapNotNull { it.toIntOrNull() } ?.takeIf { it.size == 2 && it.all { size -> size > 0 } }?.let { it[0] to it[1] } - for ((w, h) in listOfNotNull(named, width to height, long to short, short to long).distinct()) { - if (matches(gamepad, LegacyGamepadLayout(display, w, h, scale = layout.scale).elements())) return (w.toFloat() to h.toFloat()) to true + val aspectSize = layout.aspect.takeIf { layout.id == InputLibraries.OVERLAY && it > 0f } + ?.let { (it * height).roundToInt().coerceAtLeast(1) to height } + for ((w, h) in listOfNotNull(named, width to height, aspectSize, long to short, short to long).distinct()) { + val generator = LegacyGamepadLayout(display, w, h, scale = layout.scale) + if (matches(gamepad, generator.elements()) || matches(gamepad, generator.elements(previousStickGeometry = true))) return (w.toFloat() to h.toFloat()) to true } } val aspect = layout.aspect.takeIf { it > 0f } ?: (long.toFloat() / short) diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java index c75602585c..666a9d1ceb 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java +++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java @@ -12,6 +12,8 @@ import com.droiddeck.launcher.session.SessionState; import java.io.File; import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; import java.util.concurrent.atomic.AtomicIntegerArray; public final class PadBridge { @@ -56,6 +58,7 @@ public final class PadBridge { private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS]; private final PadState[] playerStates = new PadState[SLOTS]; private final float[][] rawSticks = new float[SLOTS][4]; + private final Map rightStickLayouts = new HashMap<>(); private final boolean[][] keyTriggers = new boolean[SLOTS][2]; private final int[] retainedSticks = new int[SLOTS]; private final PadState effectiveState = new PadState(); @@ -240,6 +243,7 @@ public final class PadBridge { clearBackQamWrites(); releaseBackPaddles(); activeControllerId = NO_CONTROLLER; + rightStickLayouts.clear(); for (int slot = 0; slot < SLOTS; slot++) { owners[slot] = NO_CONTROLLER; partners[slot] = NO_CONTROLLER; @@ -525,20 +529,23 @@ public final class PadBridge { float lx = event.getAxisValue(MotionEvent.AXIS_X); float ly = event.getAxisValue(MotionEvent.AXIS_Y); boolean wired = wiredXboxLayout(device, event.getSource()); - float rx = event.getAxisValue(wired ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z); - float ry = event.getAxisValue(wired ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ); + boolean rxRyStick = rightStickUsesRxRy(event, device, rightStickLayouts); + float rx = event.getAxisValue(rxRyStick ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z); + float ry = event.getAxisValue(rxRyStick ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ); retainStick(slot, JoyCon.LEFT, lx, ly); retainStick(slot, JoyCon.RIGHT, rx, ry); projectSticks(slot); int source = event.getSource(); float lt = 0f; float rt = 0f; - if (wired || hasAxis(device, source, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)) { - lt = axisTrigger(leftTrigger(event, wired), keyTriggers[slot], 0); + boolean signedLeft = signedZTriggers(event, device, wired, rxRyStick, true); + boolean signedRight = signedZTriggers(event, device, wired, rxRyStick, false); + if (signedLeft || hasAxis(device, source, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)) { + lt = axisTrigger(triggerValue(event, device, wired, rxRyStick, true), keyTriggers[slot], 0); pad.leftTrigger = lt; } - if (wired || hasAxis(device, source, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)) { - rt = axisTrigger(rightTrigger(event, wired), keyTriggers[slot], 1); + if (signedRight || hasAxis(device, source, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)) { + rt = axisTrigger(triggerValue(event, device, wired, rxRyStick, false), keyTriggers[slot], 1); pad.rightTrigger = rt; } if (hasAxis(device, source, MotionEvent.AXIS_HAT_X)) { @@ -596,6 +603,92 @@ public final class PadBridge { return false; } + static boolean rightStickUsesRxRy(MotionEvent event, InputDevice device, Map layouts) { + int source = event.getSource(); + if (wiredXboxLayout(device, source)) return true; + boolean hasRxRy = hasAxis(device, source, MotionEvent.AXIS_RX) + && hasAxis(device, source, MotionEvent.AXIS_RY); + boolean hasZRz = hasAxis(device, source, MotionEvent.AXIS_Z) + && hasAxis(device, source, MotionEvent.AXIS_RZ); + if (!hasRxRy) return false; + if (!hasZRz) return true; + Boolean cached = layouts.get(event.getDeviceId()); + if (cached != null) return cached; + boolean rxRyEvidence = atMinimum(device, source, event, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ) + && nearCentre(device, source, event, MotionEvent.AXIS_RX, MotionEvent.AXIS_RY); + boolean zRzEvidence = atMinimum(device, source, event, MotionEvent.AXIS_RX, MotionEvent.AXIS_RY) + && nearCentre(device, source, event, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ); + if (rxRyEvidence == zRzEvidence) return false; + boolean useRxRy = rxRyEvidence; + layouts.put(event.getDeviceId(), useRxRy); + return useRxRy; + } + + static boolean signedZTriggers(MotionEvent event, InputDevice device, boolean wired, boolean rxRyStick, boolean left) { + if (wired) return true; + if (!rxRyStick) return false; + int source = event.getSource(); + int signedAxis = left ? MotionEvent.AXIS_Z : MotionEvent.AXIS_RZ; + int dedicatedAxis = left ? MotionEvent.AXIS_LTRIGGER : MotionEvent.AXIS_RTRIGGER; + int alternateAxis = left ? MotionEvent.AXIS_BRAKE : MotionEvent.AXIS_GAS; + return hasAxis(device, source, signedAxis) + && !hasAxis(device, source, dedicatedAxis, alternateAxis); + } + + static float triggerValue(MotionEvent event, InputDevice device, boolean wired, boolean rxRyStick, boolean left) { + if (signedZTriggers(event, device, wired, rxRyStick, left)) { + int axis = left ? MotionEvent.AXIS_Z : MotionEvent.AXIS_RZ; + float value = event.getAxisValue(axis); + if (!wired && device != null) { + InputDevice.MotionRange range = device.getMotionRange(axis, event.getSource()); + if (range != null && range.getMax() > range.getMin()) { + return Math.max(0f, Math.min(1f, + (value - range.getMin()) / (range.getMax() - range.getMin()))); + } + } + return Math.max(0f, Math.min(1f, (value + 1f) / 2f)); + } + int source = event.getSource(); + int axis = left ? MotionEvent.AXIS_LTRIGGER : MotionEvent.AXIS_RTRIGGER; + int alternate = left ? MotionEvent.AXIS_BRAKE : MotionEvent.AXIS_GAS; + if (device == null) { + float value = event.getAxisValue(axis); + return value != 0f ? value : event.getAxisValue(alternate); + } + if (hasAxis(device, source, axis)) { + float value = event.getAxisValue(axis); + return value != 0f ? value : event.getAxisValue(alternate); + } + if (hasAxis(device, source, alternate)) return event.getAxisValue(alternate); + return 0f; + } + + private static float restDistance(InputDevice device, int source, MotionEvent event, int xAxis, int yAxis) { + return (restDistance(device.getMotionRange(xAxis, source), event.getAxisValue(xAxis)) + + restDistance(device.getMotionRange(yAxis, source), event.getAxisValue(yAxis))) / 2f; + } + + private static float restDistance(InputDevice.MotionRange range, float value) { + float span = range.getMax() - range.getMin(); + if (span <= 0f) return 1f; + return Math.abs(value - (range.getMin() + range.getMax()) / 2f) / span; + } + + private static boolean atMinimum(InputDevice device, int source, MotionEvent event, int xAxis, int yAxis) { + return atMinimum(device.getMotionRange(xAxis, source), event.getAxisValue(xAxis)) + && atMinimum(device.getMotionRange(yAxis, source), event.getAxisValue(yAxis)); + } + + private static boolean atMinimum(InputDevice.MotionRange range, float value) { + float span = range.getMax() - range.getMin(); + return value - range.getMin() <= span * 0.02f; + } + + private static boolean nearCentre(InputDevice device, int source, MotionEvent event, int xAxis, int yAxis) { + return restDistance(device.getMotionRange(xAxis, source), event.getAxisValue(xAxis)) <= 0.1f + && restDistance(device.getMotionRange(yAxis, source), event.getAxisValue(yAxis)) <= 0.1f; + } + public interface TouchRoute { boolean active(); @@ -1182,16 +1275,4 @@ public final class PadBridge { && device.getMotionRange(MotionEvent.AXIS_RZ, source) != null; } - public static float leftTrigger(MotionEvent event, boolean wired) { - if (wired) return Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_Z) + 1f) / 2f)); - float value = event.getAxisValue(MotionEvent.AXIS_LTRIGGER); - return value != 0f ? value : event.getAxisValue(MotionEvent.AXIS_BRAKE); - } - - public static float rightTrigger(MotionEvent event, boolean wired) { - if (wired) return Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_RZ) + 1f) / 2f)); - float value = event.getAxisValue(MotionEvent.AXIS_RTRIGGER); - return value != 0f ? value : event.getAxisValue(MotionEvent.AXIS_GAS); - } - } diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadMouse.kt b/app/src/main/java/com/droiddeck/launcher/input/PadMouse.kt index 2d71451ccf..dccba8a1b6 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadMouse.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/PadMouse.kt @@ -42,6 +42,7 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S private val total = Sticks() private val triggerAxes = HashMap() private val wiredLayout = HashMap() + private val rightStickLayouts = HashMap() private val down = HashMap>() private val sent = HashMap() private val held = LinkedHashMap() @@ -87,14 +88,21 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S fun onMotion(event: MotionEvent): Boolean { if (event.actionMasked != MotionEvent.ACTION_MOVE) return true val sticks = physical.getOrPut(event.deviceId) { Sticks() } - val wired = wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(event) } + val device = event.device + val wired = wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(device, event.source) } + val rxRyStick = PadBridge.rightStickUsesRxRy(event, device, rightStickLayouts) sticks.leftX = event.getAxisValue(MotionEvent.AXIS_X) sticks.leftY = event.getAxisValue(MotionEvent.AXIS_Y) - sticks.rightX = scrollAxis(event, if (wired) MotionEvent.AXIS_RX else MotionEvent.AXIS_Z) - sticks.rightY = scrollAxis(event, if (wired) MotionEvent.AXIS_RY else MotionEvent.AXIS_RZ) - if (hasTriggerAxes(event)) { - sticks.leftTrigger = PadBridge.leftTrigger(event, wired) - sticks.rightTrigger = PadBridge.rightTrigger(event, wired) + sticks.rightX = scrollAxis(event, if (rxRyStick) MotionEvent.AXIS_RX else MotionEvent.AXIS_Z) + sticks.rightY = scrollAxis(event, if (rxRyStick) MotionEvent.AXIS_RY else MotionEvent.AXIS_RZ) + val signedLeft = PadBridge.signedZTriggers(event, device, wired, rxRyStick, true) + val signedRight = PadBridge.signedZTriggers(event, device, wired, rxRyStick, false) + val analogTriggers = hasTriggerAxes(event) + if (analogTriggers || signedLeft) { + sticks.leftTrigger = PadBridge.triggerValue(event, device, wired, rxRyStick, true) + } + if (analogTriggers || signedRight) { + sticks.rightTrigger = PadBridge.triggerValue(event, device, wired, rxRyStick, false) } val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X) val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y) @@ -129,6 +137,7 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S physical.clear() triggerAxes.clear() wiredLayout.clear() + rightStickLayouts.clear() touch.clear() down.clear() sent.clear() @@ -207,6 +216,7 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S private fun hasTriggerAxes(event: android.view.InputEvent): Boolean = triggerAxes.getOrPut(event.deviceId) { val device = event.device ?: return@getOrPut true device.getMotionRange(MotionEvent.AXIS_LTRIGGER) != null || device.getMotionRange(MotionEvent.AXIS_BRAKE) != null || + device.getMotionRange(MotionEvent.AXIS_RTRIGGER) != null || device.getMotionRange(MotionEvent.AXIS_GAS) != null || (event is MotionEvent && wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(event) }) } diff --git a/app/src/main/java/com/droiddeck/launcher/input/ScrollTouchGestures.kt b/app/src/main/java/com/droiddeck/launcher/input/ScrollTouchGestures.kt index 4f1ebc9bdd..06da1bae21 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/ScrollTouchGestures.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/ScrollTouchGestures.kt @@ -42,6 +42,7 @@ class ScrollTouchGestures( private var flingY = 0f private var flingAt = 0L private var flinging = false + var clicks = true private val longPress = Runnable { held = true @@ -86,7 +87,7 @@ class ScrollTouchGestures( lastY = startY tracker = VelocityTracker.obtain().also { it.addMovement(event) } listener.onMove(startX, startY) - handler.postDelayed(longPress, TouchTiming.HOLD_MS) + if (clicks) handler.postDelayed(longPress, TouchTiming.HOLD_MS) } MotionEvent.ACTION_MOVE -> { val index = event.findPointerIndex(pointerId).takeIf { it >= 0 } ?: return true @@ -153,6 +154,7 @@ class ScrollTouchGestures( private fun click(button: Int) { releaseClick() + if (!clicks) return listener.onButton(button, true) clicked = button handler.postDelayed(clickUp, TouchTiming.CLICK_MS) diff --git a/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt b/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt index 2d0006925f..590ef4fc08 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt @@ -40,6 +40,18 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindi data class SecondScreenDisplay(val id: Int, val label: String) object SecondScreenDisplays { + fun selection(selected: Int, available: List, gameRequested: Boolean): Int = + if (selected in available || gameRequested && selected >= 0) selected else available.firstOrNull() ?: -1 + + fun selection(selected: Int, available: List, gameRequested: Boolean, save: (Int) -> Unit): Int = + selection(selected, available, gameRequested).also { if (it != selected) save(it) } + + fun keyboardOnPrimary(gameRequested: Boolean, selected: Int, available: List, visible: Boolean = true, taken: (Int) -> Boolean): Boolean = + visible && gameRequested && selected >= 0 && (selected !in available || taken(selected)) + + fun routeKeyboard(steam: Boolean, enabled: Boolean, panel: Boolean, dock: Boolean, primaryFallback: Boolean): Boolean = + steam && enabled && (panel || dock || primaryFallback) + fun available(displayManager: DisplayManager, primaryDisplayId: Int = Display.DEFAULT_DISPLAY): List = displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION) .asSequence() diff --git a/app/src/main/java/com/droiddeck/launcher/input/TouchpadGestures.kt b/app/src/main/java/com/droiddeck/launcher/input/TouchpadGestures.kt index ed4e87732b..659b99c0ce 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/TouchpadGestures.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/TouchpadGestures.kt @@ -17,6 +17,11 @@ class TouchpadGestures( var bounds: android.graphics.RectF = android.graphics.RectF(0f, 0f, 1f, 1f) var sensitivity = 1.15f var desktop = false + var clicks = true + set(value) { + if (field != value) lastTapAt = 0L + field = value + } private val handler = Handler(Looper.getMainLooper()) private var lastX = 0f @@ -50,12 +55,17 @@ class TouchpadGestures( held = true dragging = true listener.onLongPress() - listener.onButton(PointerGestures.BTN_LEFT, true, x, y) + press(PointerGestures.BTN_LEFT) } private val clickUp = Runnable { releaseClick() } + private fun press(button: Int) { + if (clicks) listener.onButton(button, true, x, y) + } + private fun click(button: Int) { releaseClick() + if (!clicks) return listener.onButton(button, true, x, y) clicked = button handler.postDelayed(clickUp, TouchTiming.CLICK_MS) @@ -108,12 +118,12 @@ class TouchpadGestures( travelled = 0f; held = false; twoFingers = false; scrolled = false; secondWasTap = false fingers = 1; pinching = false anchorId = event.getPointerId(0); moverId = -1; holdDrag = false; scrollLocked = false - if (event.eventTime - lastTapAt < TouchTiming.DOUBLE_TAP_MS) { + if (clicks && event.eventTime - lastTapAt < TouchTiming.DOUBLE_TAP_MS) { dragging = true - listener.onButton(PointerGestures.BTN_LEFT, true, x, y) + press(PointerGestures.BTN_LEFT) } else { dragging = false - handler.postDelayed(longPress, TouchTiming.HOLD_MS) + if (clicks) handler.postDelayed(longPress, TouchTiming.HOLD_MS) } return true } @@ -153,7 +163,7 @@ class TouchpadGestures( secondWasTap = false if (!dragging) { dragging = true - listener.onButton(PointerGestures.BTN_LEFT, true, x, y) + press(PointerGestures.BTN_LEFT) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index b9e7215dc0..ed43345497 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -1428,6 +1428,28 @@ class SessionService : Service() { } catch (e: Exception) { Log.w(TAG, "steam library: the list could not be written; the card alone this session", e) } + if (SessionState.mode == MODE_DESKTOP) { + try { + val listing = File(filesDir, "session/desktop-volumes.json").apply { parentFile?.mkdirs() } + val volumes = org.json.JSONArray() + var room = if (ProotFastPath.enabled(this)) { + ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds).size + } else Int.MAX_VALUE + for (root in com.droiddeck.launcher.files.StorageRoots.list(this)) { + if (!root.removable || !root.readable) continue + val path = root.dir.absolutePath + if (':' in path || '|' in path || room <= 0) continue + binds.add(path) + room-- + volumes.put(org.json.JSONObject().put("path", path).put("label", root.label)) + } + listing.writeText(volumes.toString()) + val envAt = guest.indexOf(LinuxRuntime.SESSION_SCRIPT).takeIf { it >= 0 } ?: guest.size + guest.add(envAt, "BL_DESKTOP_VOLUMES=" + listing.path) + } catch (e: Exception) { + Log.w(TAG, "desktop volumes: the list could not be written", e) + } + } return binds } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt index ddf5838be8..065b2183ff 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt @@ -59,7 +59,7 @@ import com.droiddeck.launcher.input.* import com.droiddeck.launcher.session.SessionState private data class SurfaceSnapshot(val elements: List, val actions: Map, - val clicks: Map, val scale: Float) + val clicks: Map, val scale: Float, val aspect: Float) private class GamepadScaler(private val context: android.content.Context, private val width: Int, private val height: Int) { private fun generator(scale: Float) = LegacyGamepadLayout(context, width, height, scale = scale) @@ -83,6 +83,7 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB var clickProperties by mutableStateOf(false) var history by mutableStateOf>(emptyList()) var layoutScale by mutableFloatStateOf(layout.scale) + var aspect by mutableFloatStateOf(layout.aspect) private var scaleBase by mutableStateOf, List, Float>?>(null) private var scaleValue by mutableIntStateOf(100) private val rescales get() = gamepad != null && elements.any { it.id in gamepad.ids } @@ -94,9 +95,14 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB val positioned get() = (if (rescales) gamepad!!.reset(elements) else defaults?.let { elements.withPositionsOf(it) }) ?.takeIf { it != elements || rescales && layoutScale != 1f } val element get() = elements.firstOrNull { it.id == selected } - val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale - fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale)).takeLast(40) } - fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; history = history.dropLast(1) } } + val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale || aspect != layout.aspect + fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale, aspect)).takeLast(40) } + fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; aspect = it.aspect; history = history.dropLast(1) } } + fun beginEdit(displayed: List, aspect: Float) { + checkpoint() + elements = OnScreenLayout.editorFrame(layout.copy(elements = elements), displayed) + this.aspect = aspect + } fun scaleAll(percent: Int) { val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { checkpoint() } val factor = percent / 100f @@ -112,10 +118,6 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB fun clickAction(e: InputSurfaceElement) = preset.copy(elements = actions, clicks = clicks).clickAction(e) } -@Suppress("DEPRECATION") -private fun displayAspect(display: Display): Float? = android.util.DisplayMetrics().also(display::getRealMetrics) - .takeIf { it.widthPixels > 0 && it.heightPixels > 0 }?.let { (it.widthPixels.toFloat() / it.heightPixels).coerceIn(.05f, 20f) } - @Composable fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> Unit, role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null) { @@ -153,7 +155,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> InputLibraries.update(context) { latest -> val l = latest.layouts.first { it.id == savedLayout.id } val p = latest.preset(savedBindings.id) - latest.withLayout(l.copy(elements = draft.elements, aspect = target?.let(::displayAspect) ?: l.aspect, scale = draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } }, + latest.withLayout(l.copy(elements = draft.elements, aspect = draft.aspect, scale = draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } }, clicks = draft.clicks.filterKeys { id -> draft.elements.any { it.id == id && it.hasClick } })) } }.onSuccess { onChanged(); onDismiss() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) } @@ -253,10 +255,10 @@ private fun SurfaceCanvas(draft: SurfaceDraft, transparent: Boolean = false) { AndroidView(factory = { InputSurfaceEditorView(it) }, modifier = Modifier.fillMaxSize().testTag("input-layout-canvas"), update = { view -> view.setBackgroundColor(if (transparent) android.graphics.Color.TRANSPARENT else android.graphics.Color.rgb(10, 11, 13)) - view.style = draft.layout.style.copy(hidden = emptySet()); view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap + view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout; view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap view.isEnabled = !draft.properties && !draft.adding view.onSelect = { if (!draft.properties) draft.selected = it } - view.onBeginEdit = draft::checkpoint + view.onBeginEdit = draft::beginEdit view.onChange = { e -> if (!draft.properties) draft.elements = draft.elements.map { if (it.id == e.id) e else it } } }) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt index d03eaa6e9f..e71aba6a59 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt @@ -9,6 +9,8 @@ import android.view.HapticFeedbackConstants import android.view.MotionEvent import android.view.ViewConfiguration import android.widget.FrameLayout +import com.droiddeck.launcher.input.OnScreenLayout +import com.droiddeck.launcher.input.SavedInputLayout import com.droiddeck.launcher.input.InputSurfaceElement import com.droiddeck.launcher.input.InputSurfaceStyle import com.droiddeck.launcher.input.snapSurfaceElement @@ -16,7 +18,11 @@ import kotlin.math.abs internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { var elements: List = emptyList() - set(value) { field = value; preview.updateCustomLayout(value); invalidate() } + set(value) { field = value; refreshElements(); invalidate() } + var aspect = 1f + set(value) { field = value; refreshElements(); invalidate() } + var sourceLayout: SavedInputLayout? = null + set(value) { field = value; refreshElements(); invalidate() } var style = InputSurfaceStyle() set(value) { field = value; preview.updateStyle(value) } var snap = true @@ -26,7 +32,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { var selected: String? = null set(value) { field = value; invalidate() } var onSelect: (String?) -> Unit = {} - var onBeginEdit: () -> Unit = {} + var onBeginEdit: (List, Float) -> Unit = { _, _ -> } var onChange: (InputSurfaceElement) -> Unit = {} private val preview = InputSurfaceView(context) private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.rgb(26, 159, 255); strokeWidth = 2 * resources.displayMetrics.density } @@ -37,17 +43,31 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { private var corner = 0 private var dragging = false + private var visibleElements: List = emptyList() + init { setBackgroundColor(Color.rgb(10, 11, 13)) addView(preview, LayoutParams(-1, -1)) } + private fun refreshElements() { + visibleElements = sourceLayout?.let { layout -> + OnScreenLayout.editorElements(context, layout.copy(elements = elements, aspect = aspect), width, height) + } ?: elements + preview.updateCustomLayout(visibleElements) + } + + override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { + super.onSizeChanged(w, h, oldw, oldh) + refreshElements() + } + override fun dispatchDraw(canvas: Canvas) { super.dispatchDraw(canvas) paint.style = Paint.Style.STROKE guideX?.let { canvas.drawLine(width * it, 0f, width * it, height.toFloat(), paint) } guideY?.let { canvas.drawLine(0f, height * it, width.toFloat(), height * it, paint) } - val e = elements.firstOrNull { it.id == selected } ?: return + val e = visibleElements.firstOrNull { it.id == selected } ?: return val l = width * e.x; val t = height * e.y; val r = l + width * e.width; val b = t + height * e.height paint.style = Paint.Style.STROKE; canvas.drawRect(l, t, r, b, paint) paint.style = Paint.Style.FILL @@ -65,7 +85,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { MotionEvent.ACTION_DOWN -> { clearGuides() downX = event.x; downY = event.y; dragging = false; corner = 0 - val current = elements.firstOrNull { it.id == selected } + val current = visibleElements.firstOrNull { it.id == selected } if (current != null) { val left = width * current.x; val top = height * current.y val right = left + width * current.width; val bottom = top + height * current.height @@ -73,7 +93,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { val vertical = if (abs(downY - top) < radius) 4 else if (abs(downY - bottom) < radius) 8 else 0 if (horizontal != 0 && vertical != 0) corner = horizontal or vertical } - original = if (corner != 0) current else elements.asReversed().firstOrNull { + original = if (corner != 0) current else visibleElements.asReversed().firstOrNull { downX / width in it.x..(it.x + it.width) && downY / height in it.y..(it.y + it.height) } selected = original?.id; onSelect(selected) @@ -81,7 +101,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { MotionEvent.ACTION_MOVE -> { val e = original ?: return true if (!dragging && abs(event.x - downX) + abs(event.y - downY) > ViewConfiguration.get(context).scaledTouchSlop) { - dragging = true; onBeginEdit() + dragging = true; onBeginEdit(visibleElements, width.toFloat() / height) } if (!dragging) return true val dx = (event.x - downX) / width; val dy = (event.y - downY) / height @@ -93,7 +113,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { val bottom = if (corner and 8 != 0) (e.y + e.height + dy).coerceIn(top + .03f, 1f) else e.y + e.height e.copy(x = left, y = top, width = right - left, height = bottom - top).bounded() } - val aligned = if (snap) snapSurfaceElement(next, elements.filter { it.id != e.id }, 9 * resources.displayMetrics.density / width, + val aligned = if (snap) snapSurfaceElement(next, visibleElements.filter { it.id != e.id }, 9 * resources.displayMetrics.density / width, 9 * resources.displayMetrics.density / height, corner) else null if (aligned != null && (aligned.x != null && aligned.x != guideX || aligned.y != null && aligned.y != guideY)) performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK) guideX = aligned?.x; guideY = aligned?.y diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt index f121a9a73a..0058224c01 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt @@ -48,7 +48,7 @@ class InputSurfaceView( context: Context, private val pad: PadBridge? = null, private var customLayout: List = emptyList(), - private val inputRole: InputRole = InputRole.SECONDARY, + val inputRole: InputRole = InputRole.SECONDARY, private var surfaceStyle: InputSurfaceStyle = InputSurfaceStyle(), private val haptics: Boolean = inputRole != InputRole.PRIMARY, ) : FrameLayout(context) { @@ -59,6 +59,7 @@ class InputSurfaceView( private var requestedLayout = customLayout init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) } + val shownElements: List get() = customLayout var onTouchMiss: ((MotionEvent) -> Unit)? = null private var forwardedPointers = 0 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt index 578c936ad6..62f3c61f6c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt @@ -63,7 +63,8 @@ class SecondScreenPresentation( private var imeSeen = false private var fieldKeyboard = false private var terminalPanel: SessionTerminalPanel? = null - private var controlsView: InputSurfaceView? = null + var controlsView: InputSurfaceView? = null + private set private var created = false init { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 7584c5d4d2..dd737b1d3a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -262,6 +262,7 @@ class DrawerActions( val secondScreenNone: Boolean = true, val gameOnBottom: Boolean = false, val gameSwapAvailable: Boolean = false, + val gameSwapBuiltIn: Boolean = true, val onGameOnBottom: (Boolean) -> Unit = {}, val dashboardAvailable: Boolean = false, val desktopAvailable: Boolean = false, @@ -1303,7 +1304,8 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) } 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)), + if (a.gameSwapBuiltIn) listOf(false to stringResource(R.string.swap_game_screen_top), true to stringResource(R.string.swap_game_screen_bottom)) + else listOf(false to stringResource(R.string.main_primary), true to stringResource(R.string.main_secondary)), a.gameOnBottom, chipModifier = track("game-screen"), onPick = a.onGameOnBottom) } } diff --git a/app/src/main/res/values-ro/input_library.xml b/app/src/main/res/values-ro/input_library.xml index e277e65abf..5a3648d509 100644 --- a/app/src/main/res/values-ro/input_library.xml +++ b/app/src/main/res/values-ro/input_library.xml @@ -29,7 +29,7 @@ Cruce Trăgaci Gata - Anulează + Anulează ultima acțiune + Adaugă Trage pentru a muta. Trage de un colț pentru a redimensiona. Atinge Proprietăți pentru a atribui o acțiune. Editare pe ecranul secundar diff --git a/app/src/main/res/values-uk/input_library.xml b/app/src/main/res/values-uk/input_library.xml index c00c0b1a39..f2504dde51 100644 --- a/app/src/main/res/values-uk/input_library.xml +++ b/app/src/main/res/values-uk/input_library.xml @@ -29,7 +29,7 @@ Хрестовина Тригер Готово - Скасувати + Скасувати дію + Додати Перетягніть, щоб перемістити. Потягніть за кут, щоб змінити розмір. Торкніться «Властивості», щоб призначити дію. Редагування на другому екрані diff --git a/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt b/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt index c510dc72f3..7409d4558b 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt @@ -29,6 +29,26 @@ class DualScreenTest { assertFalse(DualScreen.isBuiltIn(5, "AYN Thor")) } + @Test @Config(sdk = [34]) fun selectedInternalAndExternalDisplaysCanBeUsed() { + withDisplay(INTERNAL, "Bottom screen") { internal -> + assertEquals(internal.displayId, DualScreen.selectedSessionDisplay(context, displays, Display.DEFAULT_DISPLAY, internal.displayId)?.displayId) + } + withDisplay(EXTERNAL, "HDMI Screen") { external -> + assertEquals(external.displayId, DualScreen.selectedSessionDisplay(context, displays, Display.DEFAULT_DISPLAY, external.displayId)?.displayId) + SessionPrefs.setDualScreenSessionMode(context, DualScreen.MODE_OFF) + assertNull(DualScreen.selectedSessionDisplay(context, displays, Display.DEFAULT_DISPLAY, external.displayId)) + SessionPrefs.setDualScreenSessionMode(context, DualScreen.MODE_AUTO) + } + } + + @Test @Config(sdk = [34]) fun missingOrRemovedSelectedDisplaysCannotBeUsed() { + assertNull(DualScreen.selectedSessionDisplay(context, displays, Display.DEFAULT_DISPLAY, Display.INVALID_DISPLAY)) + val id = ShadowDisplayManager.addDisplay("w640dp-h480dp", EXTERNAL) + shadowOf(displays.getDisplay(id)).setFlags(Display.FLAG_PRESENTATION) + ShadowDisplayManager.removeDisplay(id) + assertNull(DualScreen.selectedSessionDisplay(context, displays, Display.DEFAULT_DISPLAY, id)) + } + @Test fun knownModelsCountWhenTheTypeIsHidden() { assertTrue(DualScreen.isBuiltIn(null, "Retroid Pocket Duo")) assertTrue(DualScreen.isBuiltIn(null, " AYN Thor ")) diff --git a/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt index 44ad82b904..a7a1138957 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt @@ -162,6 +162,23 @@ class InputLayoutToolsTest { assertEquals(label, emptyList>(), overlapping(elements, width, height)) } + private fun assertStickView(elements: List, width: Int, height: Int, label: String) { + for (control in listOf(InputControl.LS, InputControl.RS)) { + val stick = elements.first { it.control == control } + assertTrue("$label ${stick.id} keeps its widened travel width", stick.width * width >= stick.height * height * 1.25f - 1f) + assertTrue("$label ${stick.id} stays on screen", stick.x >= 0f && stick.x + stick.width <= 1.0001f) + } + } + + @Test fun sticksKeepTheirFullViewAtSurfaceEdges() { + for ((width, height) in listOf(2608 to 1200, 1920 to 1080, 1280 to 960)) { + ControllerPrefs.setLayout(context, width, height, mapOf("ls" to (0f to .5f), "rs" to (1f to .5f))) + val elements = LegacyGamepadLayout(context, width, height).elements() + assertStickView(elements, width, height, "$width x $height") + ControllerPrefs.resetLayout(context, width, height) + } + } + @Test @Config(qualifiers = "w833dp-h468dp-land-369dpi") fun buttonSizeKeepsTheGamepadShapeAtHandheldDensity() { for ((w, h) in listOf(1920 to 1080, 1920 to 1200)) { @@ -191,4 +208,10 @@ class InputLayoutToolsTest { } } } + + @Test @Config(qualifiers = "w745dp-h343dp-land-420dpi") + fun wideHighDensityGamepadKeepsItsShape() { + val elements = LegacyGamepadLayout(context, 2608, 1200).elements() + assertGamepadShape(elements, 2608, 1200, "2608 x 1200") + } } diff --git a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt index 4bfa52f518..9c81655b0a 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt @@ -592,4 +592,45 @@ class InputLibraryTest { assertEquals(old.preset(InputStockLayouts.TRACKPAD), upgraded.preset(InputStockLayouts.TRACKPAD)) assertEquals(InputStockLayouts.layouts().single { it.id == InputLibraries.DECK }.elements, upgraded.layouts.single { it.id == InputLibraries.DECK }.elements) } + + @Test fun stockSecondScreenPanelsKeepTapsClicking() { + val library = InputLibraries.read(context) + for (desktop in listOf(false, true)) for (panel in listOf(null, InputStockLayouts.TRACKPAD) + DeckPanel.entries.map { it.bindings }) { + val shown = library.panelLayout(desktop, panel)!!.elements + assertTrue(shown.isNotEmpty()) + assertFalse(library.compileActive(desktop, panel).showsMouseButton(InputRole.SECONDARY, shown, library.compileStock(desktop, panel))) + } + } + + @Test fun userBoundSecondScreenMouseButtonIsDetected() { + val stock = InputLibraries.read(context) + val grips = DeckPanel.GRIPS.bindings + val button = stock.panelLayout(false, grips)!!.elements.first { it.control.dimensions == 1 } + val bound = stock.withPreset(stock.preset(grips).copy(elements = mapOf(button.id to InputAction.MouseButton(272)))) + for (desktop in listOf(false, true)) { + assertTrue(bound.compileActive(desktop, grips).showsMouseButton(InputRole.SECONDARY, listOf(button), bound.compileStock(desktop, grips))) + assertFalse(bound.compileActive(desktop, grips).showsMouseButton(InputRole.PRIMARY, listOf(button), bound.compileStock(desktop, grips))) + } + val pad = stock.panelLayout(true, InputStockLayouts.TRACKPAD)!!.elements.single() + val rebound = stock.withPreset(stock.preset(InputStockLayouts.TRACKPAD).let { it.copy(clicks = it.clicks + (pad.id to InputAction.MouseButton(273))) }) + assertTrue(rebound.compileActive(true).showsMouseButton(InputRole.SECONDARY, listOf(pad), rebound.compileStock(true))) + } + + @Test fun copiedStockPanelsKeepTapsClickingUntilAMouseButtonIsAdded() { + val stock = InputLibraries.read(context) + for (desktop in listOf(false, true)) { + val source = stock.panelLayout(desktop, null)!! + val copied = stock.useLayout(stock.activeId(desktop), InputRole.SECONDARY, source.id, shared = false) + val layout = copied.activeLayout(desktop, InputRole.SECONDARY)!! + assertNotEquals(source.id, layout.id) + assertEquals(source.id, layout.origin) + assertFalse(copied.compileActive(desktop).showsMouseButton(InputRole.SECONDARY, layout.elements, copied.compileStock(desktop))) + val added = InputSurfaceElement(InputControl.A, .4f, .4f, .1f, .1f, id = "custom:added") + val grown = copied.withLayout(layout.copy(elements = layout.elements + added)) + val bindings = grown.activePart(desktop, InputRole.SECONDARY).bindings + val bound = grown.withPreset(grown.preset(bindings).let { it.copy(elements = it.elements + (added.id to InputAction.MouseButton(272))) }) + assertTrue(bound.compileActive(desktop).showsMouseButton(InputRole.SECONDARY, layout.elements + added, bound.compileStock(desktop))) + assertFalse(bound.compileActive(desktop).showsMouseButton(InputRole.SECONDARY, layout.elements, bound.compileStock(desktop))) + } + } } diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt index 0a95382937..cfe027586a 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt @@ -49,6 +49,83 @@ class OnScreenLayoutTest { } } + @Test @Config(qualifiers = "w745dp-h343dp-land-420dpi") + fun aBuiltInGamepadSavedAtTheDisplaySizeRegeneratesForTheMeasuredSurface() { + val saved = gamepad().copy(elements = LegacyGamepadLayout(context, 2608, 1200).elements(), aspect = 2608f / 1200) + val placed = OnScreenLayout.elements(context, saved, 2048, 1200, Rect()) + assertEquals(LegacyGamepadLayout(context, 2048, 1200).regenerate(saved.elements), placed) + } + + @Test @Config(qualifiers = "w745dp-h343dp-land-420dpi") + fun previouslyGeneratedEdgeSticksRegenerateWithoutOverridingCustomGeometry() { + val w = 2608 + val h = 1200 + ControllerPrefs.setLayout(context, w, h, mapOf("ls" to (0f to .5f), "rs" to (1f to .5f))) + val generator = LegacyGamepadLayout(context, w, h) + val old = generator.elements(previousStickGeometry = true) + val current = generator.elements() + assertTrue(old.filter { it.control == InputControl.LS || it.control == InputControl.RS }.zip(current.filter { it.control == InputControl.LS || it.control == InputControl.RS }).any { (a, b) -> kotlin.math.abs(a.width - b.width) > .01f }) + val saved = gamepad().copy(elements = old, aspect = w.toFloat() / h) + assertEquals(LegacyGamepadLayout(context, 2048, h).regenerate(old), OnScreenLayout.elements(context, saved, 2048, h, Rect())) + val custom = saved.copy(elements = old.map { if (it.id == "legacy:a") it.copy(x = .4f) else it }) + assertEquals(OnScreenLayout.fit(custom.elements, custom.aspect, 1f, 2048, h, Rect()), OnScreenLayout.elements(context, custom, 2048, h, Rect())) + } + + @Test fun savingTheEditorFrameKeepsEveryControlWhereTheEditorShowsIt() { + val w = 2608 + val h = 1200 + val layout = SavedInputLayout("custom", "Custom", listOf( + InputSurfaceElement(InputControl.A, .1f, .2f, .1f, .2f, "custom:a"), + InputSurfaceElement(InputControl.B, .7f, .6f, .1f, .2f, "custom:b")), aspect = 16f / 9f) + val displayed = OnScreenLayout.editorElements(context, layout, w, h, edited = true) + val moved = displayed.map { if (it.id == "custom:a") it.copy(x = .4f) else it } + val frame = OnScreenLayout.editorFrame(layout, moved + InputSurfaceElement(InputControl.X, .5f, .5f, .1f, .1f, "builtin:keyboard")) + assertEquals(layout.elements.map { it.id }, frame.map { it.id }) + val saved = layout.copy(elements = frame, aspect = w.toFloat() / h) + val game = OnScreenLayout.elements(context, saved, w, h, Rect()) + val editor = OnScreenLayout.editorElements(context, saved, w, h, edited = true) + for (shown in moved) { + assertArrayEquals(px(shown, w, h), px(game.first { it.id == shown.id }, w, h), .001f) + assertArrayEquals(px(shown, w, h), px(editor.first { it.id == shown.id }, w, h), .001f) + } + } + + @Test fun editorAndGameUseTheSamePixelRectsOnWideAndStandardScreens() { + val layout = gamepad() + for ((w, h) in listOf(2000 to 900, 1600 to 900)) { + val game = OnScreenLayout.elements(context, layout, w, h, Rect()) + val editor = OnScreenLayout.editorElements(context, layout, w, h) + assertEquals(game.map { it.id }, editor.map { it.id }) + game.zip(editor).forEach { (gameElement, editorElement) -> + assertArrayEquals(px(gameElement, w, h), px(editorElement, w, h), .001f) + } + } + } + + @Test fun editedGeneratedAndCustomLayoutsKeepTheirPixelRectsAcrossRefreshes() { + for ((w, h) in listOf(2000 to 900, 1600 to 900)) { + val generated = gamepad() + val generatedEdit = generated.elements.map { if (it.id == "legacy:a") it.copy(x = .3f, y = .4f, width = .12f, height = .12f) else it } + val generatedSaved = generated.copy(elements = generatedEdit, aspect = w.toFloat() / h) + val generatedPixels = px(OnScreenLayout.elements(context, generatedSaved, w, h, Rect()).first { it.id == "legacy:a" }, w, h) + val generatedRefresh = px(OnScreenLayout.editorElements(context, generatedSaved, w, h, edited = true).first { it.id == "legacy:a" }, w, h) + assertArrayEquals(generatedPixels, generatedRefresh, .001f) + + val custom = SavedInputLayout("custom", "Custom", listOf(InputSurfaceElement(InputControl.A, .3f, .4f, .12f, .12f)), aspect = w.toFloat() / h) + val customRefresh = OnScreenLayout.editorElements(context, custom, w, h, edited = true) + assertArrayEquals(px(customRefresh.single(), w, h), px(OnScreenLayout.editorElements(context, custom.copy(elements = customRefresh), w, h, edited = true).single(), w, h), .001f) + } + } + + @Test fun resetPositionsRestoresGeneratedGeometryAfterAnEdit() { + for ((w, h) in listOf(2000 to 900, 1600 to 900)) { + val original = gamepad() + val moved = original.copy(elements = original.elements.map { if (it.id == "legacy:a") it.copy(x = .3f) else it }, aspect = w.toFloat() / h) + val reset = LegacyGamepadLayout(context, w, h).regenerate(moved.elements) + assertEquals(LegacyGamepadLayout(context, w, h).regenerate(original.elements), OnScreenLayout.elements(context, moved.copy(elements = reset), w, h, Rect())) + } + } + @Test fun regenerationKeepsTheUsersButtonStylesAndRemovedButtons() { val layout = gamepad().let { g -> g.copy(elements = g.elements.filterNot { it.id == "legacy:y" }.map { if (it.id == "legacy:a") it.copy(opacity = .4f, icon = 0, name = "Jump") else it }) } val placed = OnScreenLayout.elements(context, layout, 2000, 1000, Rect()) diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenMouseButtonTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenMouseButtonTest.kt new file mode 100644 index 0000000000..aebe881c8a --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenMouseButtonTest.kt @@ -0,0 +1,71 @@ +package com.droiddeck.launcher.input + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class OnScreenMouseButtonTest { + private val button = InputSurfaceElement(InputControl.A, .8f, .6f, .1f, .1f, id = "custom:left") + private val stick = InputSurfaceElement(InputControl.LS, .1f, .6f, .2f, .3f, id = "custom:stick") + private val legacyA = InputSurfaceElement(InputControl.A, .8f, .6f, .1f, .1f) + private val game = InputProfile.defaults(InputProfile.GAME) + private val desktop = InputProfile.defaults(InputProfile.DESKTOP) + private val overlay = InputControl.entries.map { InputSurfaceElement(it, .1f, .1f, .1f, .1f) } + + private fun profile(vararg elements: Pair, clicks: Map = emptyMap(), base: InputProfile = game) = + base.copy(elements = mapOf(InputRole.PRIMARY to elements.toMap()), clicks = mapOf(InputRole.PRIMARY to clicks)) + + @Test fun shownButtonBoundToAMouseButtonIsDetected() { + listOf(272, 273, 274).forEach { code -> + assertTrue(profile(button.id to InputAction.MouseButton(code)).showsMouseButton(InputRole.PRIMARY, listOf(stick, button), game)) + } + } + + @Test fun stickClickBoundToAMouseButtonIsDetected() { + val profile = profile(stick.id to InputAction.Native(), clicks = mapOf(stick.id to InputAction.MouseButton(272))) + assertTrue(profile.showsMouseButton(InputRole.PRIMARY, listOf(stick), game)) + } + + @Test fun legacyButtonUsesItsRoleBinding() { + val profile = game.withBinding(InputRole.PRIMARY, InputControl.A, InputAction.MouseButton(272)) + assertTrue(profile.showsMouseButton(InputRole.PRIMARY, listOf(legacyA), game)) + assertFalse(profile.showsMouseButton(InputRole.SECONDARY, listOf(legacyA), game)) + } + + @Test fun stockDesktopOverlayKeepsTapsClicking() { + assertFalse(desktop.showsMouseButton(InputRole.PRIMARY, overlay, desktop)) + } + + @Test fun userBoundMouseButtonInDesktopIsDetected() { + val rebound = desktop.withBinding(InputRole.PRIMARY, InputControl.X, InputAction.MouseButton(272)) + assertTrue(rebound.showsMouseButton(InputRole.PRIMARY, overlay, desktop)) + val stickClick = desktop.withBinding(InputRole.PRIMARY, InputControl.L3, InputAction.MouseButton(274)) + assertTrue(stickClick.showsMouseButton(InputRole.PRIMARY, overlay, desktop)) + assertTrue(profile(button.id to InputAction.MouseButton(272), base = desktop).showsMouseButton(InputRole.PRIMARY, overlay + button, desktop)) + } + + @Test fun desktopBindingsOnAGameBaseProfileAreUserPicked() { + val copied = desktop.copy(id = "custom") + assertTrue(copied.showsMouseButton(InputRole.PRIMARY, overlay, game)) + } + + @Test fun layoutWithoutAMouseButtonKeepsTapsClicking() { + val profile = profile(button.id to InputAction.Keys(listOf(57)), stick.id to InputAction.Pointer()) + assertFalse(profile.showsMouseButton(InputRole.PRIMARY, listOf(stick, button), game)) + assertFalse(game.showsMouseButton(InputRole.PRIMARY, listOf(legacyA, stick) + overlay, game)) + } + + @Test fun hiddenMouseButtonDoesNotCount() { + assertFalse(profile(button.id to InputAction.MouseButton(272)).showsMouseButton(InputRole.PRIMARY, listOf(stick), game)) + assertFalse(profile(button.id to InputAction.MouseButton(272)).showsMouseButton(InputRole.PRIMARY, emptyList(), game)) + } + + @Test fun physicalMouseBindingsDoNotCount() { + val profile = game.withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.MouseButton(272)) + assertFalse(profile.showsMouseButton(InputRole.PRIMARY, listOf(legacyA), game)) + } + + @Test fun invalidMouseCodeDoesNotCount() { + assertFalse(profile(button.id to InputAction.MouseButton(1)).showsMouseButton(InputRole.PRIMARY, listOf(button), game)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/PadPartialAxesTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PadPartialAxesTest.kt index ae46c9d5e3..b79e813a9e 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/PadPartialAxesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/PadPartialAxesTest.kt @@ -83,6 +83,117 @@ class PadPartialAxesTest { assertEquals(-0.6f, pad().rightY) } + @Test fun onlyRxRyAxesProvideTheRightStick() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY) + motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f) + assertEquals(0.6f, pad().rightX) + assertEquals(-0.6f, pad().rightY) + } + + @Test fun rxRyStickWithoutZRzKeepsTriggersReleased() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY) + motion(device, MotionEvent.AXIS_RX to 0f, MotionEvent.AXIS_RY to 0f) + assertEquals(0f, pad().leftTrigger) + assertEquals(0f, pad().rightTrigger) + } + + @Test fun rxRyStickReadsDedicatedTriggerAxes() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_RTRIGGER) + motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to 0f, + MotionEvent.AXIS_LTRIGGER to 0.4f, MotionEvent.AXIS_RTRIGGER to 0f) + assertEquals(0.6f, pad().rightX) + assertEquals(0.4f, pad().leftTrigger) + assertEquals(0f, pad().rightTrigger) + } + + @Test fun leftTriggerFallsBackToBrakeWhenDedicatedAxisIsZero() { + val device = device(MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE) + motion(device, MotionEvent.AXIS_LTRIGGER to 0f, MotionEvent.AXIS_BRAKE to 0.7f) + assertEquals(0.7f, pad().leftTrigger) + } + + @Test fun rightTriggerFallsBackToGasWhenDedicatedAxisIsZero() { + val device = device(MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS) + motion(device, MotionEvent.AXIS_RTRIGGER to 0f, MotionEvent.AXIS_GAS to 0.8f) + assertEquals(0.8f, pad().rightTrigger) + } + + @Test fun onlyZRzAxesProvideTheRightStick() { + val device = device(MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ) + motion(device, MotionEvent.AXIS_Z to 0.6f, MotionEvent.AXIS_RZ to -0.6f) + assertEquals(0.6f, pad().rightX) + assertEquals(-0.6f, pad().rightY) + } + + @Test fun bothPairsUseThePairAtRestNearCentreAsTheStick() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ) + motion(device, MotionEvent.AXIS_RX to -1f, MotionEvent.AXIS_RY to -1f, + MotionEvent.AXIS_Z to 0f, MotionEvent.AXIS_RZ to 0f) + assertEquals(0f, pad().rightX) + assertEquals(0f, pad().rightY) + motion(device, MotionEvent.AXIS_RX to 0.2f, MotionEvent.AXIS_RY to -0.3f, + MotionEvent.AXIS_Z to 0.7f, MotionEvent.AXIS_RZ to -0.8f) + assertEquals(0.7f, pad().rightX) + assertEquals(-0.8f, pad().rightY) + } + + @Test fun bothPairsUseRxRyAsStickWhenZRzRestAtMinimum() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ) + motion(device, MotionEvent.AXIS_RX to 0f, MotionEvent.AXIS_RY to 0f, + MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f) + assertEquals(0f, pad().rightX) + assertEquals(0f, pad().rightY) + assertEquals(0f, pad().leftTrigger) + assertEquals(0f, pad().rightTrigger) + motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f, + MotionEvent.AXIS_Z to 1f, MotionEvent.AXIS_RZ to 1f) + assertEquals(0.6f, pad().rightX) + assertEquals(-0.6f, pad().rightY) + assertEquals(1f, pad().leftTrigger) + assertEquals(1f, pad().rightTrigger) + } + + @Test fun nonWiredZeroToOneSignedZTriggersNormalizeFromTheirRange() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ, + zeroToOneAxes = setOf(MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ)) + motion(device, MotionEvent.AXIS_RX to 0f, MotionEvent.AXIS_RY to 0f, + MotionEvent.AXIS_Z to 0f, MotionEvent.AXIS_RZ to 0f) + assertEquals(0f, pad().leftTrigger) + assertEquals(0f, pad().rightTrigger) + motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f, + MotionEvent.AXIS_Z to 1f, MotionEvent.AXIS_RZ to 1f) + assertEquals(1f, pad().leftTrigger) + assertEquals(1f, pad().rightTrigger) + } + + @Test fun movingFirstEventDoesNotLockTheWrongStickPair() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ) + motion(device, MotionEvent.AXIS_RX to 1f, MotionEvent.AXIS_RY to 0f, + MotionEvent.AXIS_Z to 0f, MotionEvent.AXIS_RZ to 0f) + assertEquals(0f, pad().rightX) + assertEquals(0f, pad().rightY) + motion(device, MotionEvent.AXIS_RX to 0f, MotionEvent.AXIS_RY to 0f, + MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f) + motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f, + MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f) + assertEquals(0.6f, pad().rightX) + assertEquals(-0.6f, pad().rightY) + } + + @Test fun dedicatedRightTriggerWinsOverSignedRightTrigger() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, + MotionEvent.AXIS_RZ, MotionEvent.AXIS_RTRIGGER) + motion(device, MotionEvent.AXIS_RX to 0f, MotionEvent.AXIS_RY to 0f, + MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f) + motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f, + MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f, + MotionEvent.AXIS_RTRIGGER to 0.7f) + assertEquals(0f, pad().leftTrigger) + assertEquals(0.7f, pad().rightTrigger) + assertEquals(0.6f, pad().rightX) + assertEquals(-0.6f, pad().rightY) + } + @Test fun sticksWithoutTriggerOrHatAxesPreserveAllDigitalControls() { val device = device() key(device, KeyEvent.KEYCODE_BUTTON_L2) @@ -208,14 +319,15 @@ class PadPartialAxesTest { try { assertTrue(bridge.onMotionEvent(event)) } finally { event.recycle() } } - private fun device(vararg axes: Int, wired: Boolean = false): InputDevice { + private fun device(vararg axes: Int, wired: Boolean = false, zeroToOneAxes: Set = emptySet()): InputDevice { val builder = InputDeviceBuilder.newBuilder().setId(60).setName("partial pad") .setDescriptor("partial-pad").setExternal(true) .setSources(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK) .setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC) .setVendorId(if (wired) 0x20d6 else 0).setProductId(if (wired) 0x2063 else 0) for (axis in axes.toList() + MotionEvent.AXIS_X) { - builder.addMotionRange(axis, InputDevice.SOURCE_JOYSTICK, -1f, 1f, 0f, 0f, 0f) + val min = if (axis in zeroToOneAxes) 0f else -1f + builder.addMotionRange(axis, InputDevice.SOURCE_JOYSTICK, min, 1f, 0f, 0f, 0f) } return builder.build().also { shadowOf(RuntimeEnvironment.getApplication().getSystemService(InputManager::class.java)).addInputDevice(it) diff --git a/app/src/test/java/com/droiddeck/launcher/input/ScrollTouchGesturesTest.kt b/app/src/test/java/com/droiddeck/launcher/input/ScrollTouchGesturesTest.kt index 60436eaabd..ea2d50c5fb 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/ScrollTouchGesturesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/ScrollTouchGesturesTest.kt @@ -131,6 +131,50 @@ class ScrollTouchGesturesTest { assertEquals(listOf("move 400,300"), events) } + @Test fun tapsAndHoldsDoNotClickWhileClicksAreOff() { + gestures.clicks = false + touch(MotionEvent.ACTION_DOWN, 400f, 300f) + advance(80) + touch(MotionEvent.ACTION_UP, 400f, 300f) + advance(100) + touch(MotionEvent.ACTION_DOWN, 400f, 300f) + advance(600) + touch(MotionEvent.ACTION_UP, 402f, 301f) + advance(100) + assertEquals(listOf("move 400,300", "move 400,300"), events) + } + + @Test fun holdThenMoveScrollsWhileClicksAreOff() { + gestures.clicks = false + touch(MotionEvent.ACTION_DOWN, 400f, 800f) + advance(600) + touch(MotionEvent.ACTION_MOVE, 402f, 500f) + advance(200) + touch(MotionEvent.ACTION_UP, 402f, 500f) + advance(100) + assertEquals(300f, scrolledY, 0.01f) + assertEquals(listOf("move 400,800"), events) + } + + @Test fun turningClicksOffReleasesAClickInFlight() { + touch(MotionEvent.ACTION_DOWN, 400f, 300f) + advance(80) + touch(MotionEvent.ACTION_UP, 400f, 300f) + gestures.clicks = false + touch(MotionEvent.ACTION_DOWN, 400f, 300f) + advance(80) + touch(MotionEvent.ACTION_UP, 400f, 300f) + advance(100) + assertEquals(listOf("move 400,300", "left down", "left up", "move 400,300"), events) + events.clear() + gestures.clicks = true + touch(MotionEvent.ACTION_DOWN, 400f, 300f) + advance(80) + touch(MotionEvent.ACTION_UP, 400f, 300f) + advance(100) + assertEquals(listOf("move 400,300", "left down", "left up"), events) + } + @Test fun aSecondFingerDoesNotJumpTheScroll() { touch(MotionEvent.ACTION_DOWN, 400f, 900f) advance(100) diff --git a/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt index 9956f1aa6d..566a091c42 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt @@ -1,9 +1,58 @@ package com.droiddeck.launcher.input import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue import org.junit.Test class SecondScreenModeTest { + @Test fun fallbackSelectionSurvivesRecreationAndRequestedDisplaySurvivesDisconnect() { + var saved = 2 + SecondScreenDisplays.selection(saved, listOf(3), false) { saved = it } + assertEquals(3, saved) + assertEquals(3, SecondScreenDisplays.selection(saved, listOf(3), true)) + SecondScreenDisplays.selection(saved, listOf(2), true) { saved = it } + assertEquals(3, saved) + } + + @Test fun keyboardFallsBackOnlyForADisconnectedRequestedDisplay() { + val taken: (Int) -> Boolean = { it == 2 } + val free: (Int) -> Boolean = { false } + assertTrue(SecondScreenDisplays.keyboardOnPrimary(true, 2, listOf(3), taken = free)) + assertTrue(SecondScreenDisplays.keyboardOnPrimary(true, 2, listOf(2, 3), taken = taken)) + assertFalse(SecondScreenDisplays.keyboardOnPrimary(true, 2, listOf(2, 3), taken = free)) + assertFalse(SecondScreenDisplays.keyboardOnPrimary(false, 2, listOf(3), taken = taken)) + assertFalse(SecondScreenDisplays.keyboardOnPrimary(true, -1, listOf(3), taken = taken)) + } + + @Test fun primaryFallbackRequiresVisibleActivity() { + for (available in listOf(emptyList(), listOf(2))) { + assertTrue(SecondScreenDisplays.keyboardOnPrimary(true, 2, available, true) { true }) + assertFalse(SecondScreenDisplays.keyboardOnPrimary(true, 2, available, false) { true }) + } + } + + @Test fun keyboardRouteIncludesOccupiedDisplayFallbackOnlyWhenEnabled() { + val fallback = SecondScreenDisplays.keyboardOnPrimary(true, 2, listOf(2)) { it == 2 } + assertTrue(fallback) + assertTrue(SecondScreenDisplays.routeKeyboard(true, true, false, false, fallback)) + assertFalse(SecondScreenDisplays.routeKeyboard(true, false, false, false, fallback)) + assertFalse(SecondScreenDisplays.routeKeyboard(false, true, false, false, fallback)) + assertFalse(SecondScreenDisplays.routeKeyboard(true, true, false, false, false)) + assertTrue(SecondScreenDisplays.routeKeyboard(true, true, true, false, false)) + assertTrue(SecondScreenDisplays.routeKeyboard(true, true, false, true, false)) + } + + @Test fun selectedGameDisplayIsNotReplacedWhenItDisconnects() { + assertEquals(2, SecondScreenDisplays.selection(2, listOf(3), true)) + assertEquals(2, SecondScreenDisplays.selection(2, emptyList(), true)) + assertEquals(2, SecondScreenDisplays.selection(2, listOf(3, 2), true)) + assertEquals(3, SecondScreenDisplays.selection(3, listOf(3), true)) + assertEquals(3, SecondScreenDisplays.selection(2, listOf(3), false)) + assertEquals(3, SecondScreenDisplays.selection(-1, listOf(3), true)) + assertEquals(-1, SecondScreenDisplays.selection(-1, emptyList(), false)) + } + @Test fun withNothingRememberedDeckPadsGetControlsAndOthersTheDashboard() { assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening(null, deckPad = true, dashboard = true)) assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening(null, deckPad = false, dashboard = true)) diff --git a/app/src/test/java/com/droiddeck/launcher/input/SessionFieldKeyboardTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SessionFieldKeyboardTest.kt new file mode 100644 index 0000000000..483c61f562 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/SessionFieldKeyboardTest.kt @@ -0,0 +1,169 @@ +package com.droiddeck.launcher.input + +import android.view.KeyEvent +import android.view.WindowInsets +import com.droiddeck.launcher.SessionActivity +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.util.ReflectionHelpers + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class SessionFieldKeyboardTest { + private lateinit var activity: SessionActivity + private lateinit var keyboard: KeyboardHost + + @Before fun setUp() { + activity = Robolectric.buildActivity(SessionActivity::class.java).get() + keyboard = KeyboardHost(activity) + ReflectionHelpers.setField(activity, "keyboard", keyboard) + keyboard.onImeChanged = { visible -> + ReflectionHelpers.callInstanceMethod(activity, "onPrimaryImeChanged", + ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, visible)) + } + } + + @Test fun guestDismissalClosesOnlyTheGuestOwnedKeyboard() { + openFieldKeyboard() + call("dismissFieldKeyboard") + assertFalse(keyboard.shown) + call("showPrimaryKeyboard") + call("dismissFieldKeyboard") + assertTrue(keyboard.shown) + } + + @Test fun pauseHideThenManualReopenSurvivesGuestDismissal() { + openFieldKeyboard() + call("hidePrimaryKeyboard") + assertFalse(keyboard.shown) + call("showPrimaryKeyboard") + call("dismissFieldKeyboard") + assertTrue(keyboard.shown) + openFieldKeyboard() + call("dismissFieldKeyboard") + assertFalse(keyboard.shown) + } + + @Test fun manualToggleAndPcKeyboardRelinquishGuestOwnership() { + openFieldKeyboard() + call("togglePrimaryKeyboard") + call("togglePrimaryKeyboard") + call("dismissFieldKeyboard") + assertTrue(keyboard.shown) + openFieldKeyboard() + call("togglePcKeyboard") + call("showPrimaryKeyboard") + call("dismissFieldKeyboard") + assertTrue(keyboard.shown) + } + + @Test fun pendingGuestRequestWaitsForFocusAndCanBeDismissed() { + ReflectionHelpers.callInstanceMethod(activity, "setGameOnBottom", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true)) + ReflectionHelpers.callInstanceMethod(activity, "setSelectedSecondScreenDisplay", ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 2)) + ReflectionHelpers.callInstanceMethod(activity, "setResumed", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true)) + call("openBottomKeyboard") + ReflectionHelpers.callInstanceMethod(activity, "retryFieldKeyboard", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, false)) + assertFalse(keyboard.shown) + call("dismissFieldKeyboard") + ReflectionHelpers.callInstanceMethod(activity, "retryFieldKeyboard", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true)) + assertFalse(keyboard.shown) + call("openBottomKeyboard") + ReflectionHelpers.callInstanceMethod(activity, "retryFieldKeyboard", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true)) + assertTrue(keyboard.shown) + call("dismissFieldKeyboard") + assertFalse(keyboard.shown) + } + + @Config(sdk = [33]) + @Test fun staleHiddenEventFromEarlierHideKeepsNewGuestOwnership() { + call("showPrimaryKeyboard") + ime(true) + call("hidePrimaryKeyboard") + requestFieldKeyboard() + ime(false) + assertTrue(owned()) + ime(true) + call("dismissFieldKeyboard") + assertFalse(keyboard.shown) + } + + @Config(sdk = [33]) + @Test fun hiddenEventAfterGuestKeyboardShowsClearsOwnership() { + requestFieldKeyboard() + ime(true) + ime(false) + assertFalse(owned()) + call("showPrimaryKeyboard") + call("dismissFieldKeyboard") + assertTrue(keyboard.shown) + } + + @Config(sdk = [33]) + @Test fun guestRequestWhileKeyboardAlreadyVisibleClearsOnRealDismissal() { + call("showPrimaryKeyboard") + ime(true) + requestFieldKeyboard() + assertTrue(owned()) + ime(false) + assertFalse(owned()) + } + + @Test fun backDismissalWithoutImeInsetsClearsOwnership() { + requestFieldKeyboard() + assertTrue(owned()) + val t = System.currentTimeMillis() + keyboard.onKeyPreIme(KeyEvent.KEYCODE_BACK, KeyEvent(t, t, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK, 0)) + assertFalse(keyboard.shown) + assertFalse(owned()) + } + + @Test fun focusReturnSkipsPrimaryKeyboardWhenDestinationNoLongerPrimary() { + setFlag("setGameOnBottom", true) + selectDisplay(2) + setFlag("setResumed", true) + call("openBottomKeyboard") + retry(false) + setFlag("setGameOnBottom", false) + retry(true) + assertFalse(keyboard.shown) + assertFalse(owned()) + assertFalse(ReflectionHelpers.getField(activity, "pendingFieldKeyboard")) + } + + private fun requestFieldKeyboard() { + setFlag("setGameOnBottom", true) + selectDisplay(2) + setFlag("setResumed", true) + call("openBottomKeyboard") + retry(true) + assertTrue(keyboard.shown) + } + + private fun ime(visible: Boolean) { + keyboard.dispatchApplyWindowInsets(WindowInsets.Builder().setVisible(WindowInsets.Type.ime(), visible).build()) + } + + private fun owned() = ReflectionHelpers.getField(activity, "fieldKeyboardOnPrimary") + + private fun selectDisplay(id: Int) = ReflectionHelpers.callInstanceMethod(activity, "setSelectedSecondScreenDisplay", + ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, id)) + + private fun retry(focus: Boolean) = ReflectionHelpers.callInstanceMethod(activity, "retryFieldKeyboard", + ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, focus)) + + private fun setFlag(name: String, value: Boolean) = ReflectionHelpers.callInstanceMethod(activity, name, + ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, value)) + + private fun openFieldKeyboard() { + ReflectionHelpers.setField(activity, "fieldKeyboardOnPrimary", true) + keyboard.show() + } + + private fun call(name: String) = ReflectionHelpers.callInstanceMethod(activity, name) +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/TouchpadGesturesTest.kt b/app/src/test/java/com/droiddeck/launcher/input/TouchpadGesturesTest.kt index 2b84e3ae4d..c967ce02fd 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/TouchpadGesturesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/TouchpadGesturesTest.kt @@ -262,6 +262,75 @@ class TouchpadGesturesTest { assertFalse(events.contains("left down")) } + @Test fun tapsDoNotClickWhileClicksAreOff() { + touchpad.clicks = false + tap() + advance(20) + tap() + advance(TouchTiming.HOLD_MS + 100) + touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f)) + advance(TouchTiming.HOLD_MS + 100) + touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f)) + advance(200) + assertFalse(events.any { it.endsWith(" down") }) + } + + @Test fun twoFingerTapDoesNotClickWhileClicksAreOff() { + touchpad.clicks = false + touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f)) + advance(10) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 310f)) + advance(60) + touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 300f), 2 to (600f to 310f)) + advance(10) + touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f)) + advance(200) + assertFalse(events.any { it.endsWith(" down") }) + } + + @Test fun pointerStillMovesWhileClicksAreOff() { + touchpad.clicks = false + touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f)) + advance(10) + touch(MotionEvent.ACTION_MOVE, 0, 1 to (440f to 300f)) + advance(10) + touch(MotionEvent.ACTION_UP, 0, 1 to (440f to 300f)) + assertTrue(events.contains("move")) + assertTrue(touchpad.x > 960f) + assertFalse(events.any { it.endsWith(" down") }) + } + + @Test fun tapsClickAgainOnceClicksAreBackOn() { + touchpad.clicks = false + tap() + advance(400) + touchpad.clicks = true + tap() + advance(200) + assertEquals(listOf("left down", "left up"), events) + } + + @Test fun aTapWhileClicksWereOffDoesNotStartADragOnceTheyAreBackOn() { + touchpad.clicks = false + tap() + advance(20) + touchpad.clicks = true + touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f)) + assertEquals(emptyList(), events) + advance(80) + touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f)) + advance(200) + assertEquals(listOf("left down", "left up"), events) + } + + @Test fun doubleTapStillDragsWhileClicksStayOn() { + tap() + advance(20) + touchpad.clicks = true + touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f)) + assertEquals(listOf("left down", "left up", "left down"), events) + } + private fun tap() { touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f)) advance(80) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt new file mode 100644 index 0000000000..c74e5be155 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt @@ -0,0 +1,76 @@ +package com.droiddeck.launcher.ui + +import android.view.MotionEvent +import com.droiddeck.launcher.input.InputControl +import com.droiddeck.launcher.input.InputSurfaceElement +import com.droiddeck.launcher.input.OnScreenLayout +import com.droiddeck.launcher.input.SavedInputLayout +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], manifest = Config.NONE) +class InputSurfaceEditorViewTest { + private val context get() = RuntimeEnvironment.getApplication() + private val layout = SavedInputLayout("custom", "Custom", listOf(InputSurfaceElement(InputControl.A, .1f, .2f, .2f, .2f)), aspect = 2f) + + private fun view() = InputSurfaceEditorView(context).apply { + layout(0, 0, 1000, 1000) + sourceLayout = layout + aspect = layout.aspect + elements = layout.elements + snap = false + } + + private fun center() = OnScreenLayout.editorElements(context, layout, 1000, 1000).first().let { (it.x + it.width / 2) * 1000 to (it.y + it.height / 2) * 1000 } + @Suppress("UNCHECKED_CAST") + private fun InputSurfaceEditorView.rendered() = javaClass.getDeclaredField("visibleElements").also { it.isAccessible = true }.get(this) as List + + private fun InputSurfaceEditorView.touch(action: Int, x: Float, y: Float) { + MotionEvent.obtain(0, 10, action, x, y, 0).also { onTouchEvent(it); it.recycle() } + } + + @Test fun editingStartsInTheDisplayedFrame() { + val view = view() + var started: Pair, Float>? = null + view.onBeginEdit = { elements, aspect -> started = elements to aspect } + val (x, y) = center() + view.touch(MotionEvent.ACTION_DOWN, x, y) + view.touch(MotionEvent.ACTION_MOVE, x + 100f, y + 50f) + val (elements, aspect) = requireNotNull(started) + assertEquals(1f, aspect, .0001f) + assertEquals(OnScreenLayout.editorElements(context, layout, 1000, 1000), elements) + } + + @Test fun undoRestoresTheSavedFrameForHitTesting() { + val view = view() + var selection: String? = null + view.onSelect = { selection = it } + view.elements = layout.elements.map { it.copy(x = .5f) } + view.elements = layout.elements + val (x, y) = center() + view.touch(MotionEvent.ACTION_DOWN, x, y) + assertEquals("legacy:a", selection) + } + + @Test fun editorFramePreservesAddedAndRemovedDraftElements() { + val added = layout.elements + InputSurfaceElement(InputControl.B, .6f, .2f, .2f, .2f, id = "added") + val removed = layout.copy(elements = emptyList()) + assertEquals(added, OnScreenLayout.editorFrame(layout.copy(elements = added), added)) + assertEquals(emptyList(), OnScreenLayout.editorFrame(removed, emptyList())) + } + + @Test fun savedAspectRemainsStableForRenamesAndResizes() { + val view = view() + val renamed = layout.elements.map { it.copy(name = "Renamed") } + view.elements = renamed + view.aspect = 2f + assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 1000, 1000), view.rendered()) + view.layout(0, 0, 800, 1000) + assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 800, 1000), view.rendered()) + } +} diff --git a/docs/development/d3d10-renderer-crash.md b/docs/development/d3d10-renderer-crash.md deleted file mode 100644 index a57e258ab5..0000000000 --- a/docs/development/d3d10-renderer-crash.md +++ /dev/null @@ -1,48 +0,0 @@ -# D3D10 renderer crash investigation - -Status: root cause unproven; no runtime change or publishable fix. - -## Evidence - -Discord message 1571620183263416432 from ThatGuy reports that the original 2007 GOG release crashes after its intro videos while the remastered release reaches the menu. The report covers application 0.7.1 on an S948U1 with Adreno 840. - -The supplied session archive identifies DroidDeck-Proton-11-12.8 and DXVK v3.1.1-221-g71bf4bad. Within the original release's Steam log: - -- Lines 11057–11058 show the game-local native d3dx10_33 DLL loading the builtin D3DCompiler_33 DLL. -- Line 11610 records a reflection GetDesc partial-stub warning on thread 01d8 at 182976.924. -- Lines 12011–12012 show the Renderer thread 01e0 compiling twice while flags 0x1000 are ignored, at about 183023.553. -- Lines 12014–12017 record an access violation reading address 8 at executable offset 0x52B090. -- Line 12132 identifies the faulting instruction as movl 8(%ecx), %eax, and line 12086 shows ECX is zero. - -The reflection warning precedes the crash by about 47 seconds on another thread. Temporal proximity does not establish causation. No failed shader-compilation diagnostic accompanies the final two compilation calls, and the loaded compiler is version 33 rather than 47. The null object's producer remains unidentified. - -## Research - -- [A matching desktop report](https://github.com/doitsujin/dxvk/issues/655#issuecomment-4697290483) has the same null-plus-8 read immediately after two ignored-0x1000 messages. Installing compiler 43 did not fix that report, arguing against assuming a device-specific fault. -- [The follow-up discussion](https://github.com/doitsujin/dxvk/issues/655#issuecomment-4698071691) calls for identifying the actual compiler dependency. -- Historical DXVK commit 8630ee235a7a97c0ad87af2703b3c06bfd8e475e addressed concurrent D3D10 device access. It is not evidence that the current compiler warning causes this crash. -- [The upstream compatibility report](https://github.com/ValveSoftware/Proton/issues/388) includes DX9 fallback reports, but also crashes when loading with DX9. DX9 is an experiment, not a verified fix. -- [Wine's reflection implementation](https://github.com/wine-mirror/wine/blob/wine-10.0/dlls/d3dcompiler_43/reflection.c#L396) fills many descriptor fields despite its partial-stub warning. The warning alone does not establish a null return. -- Wine commit 815fe9deb15b2cc742a243166316a1d33c6a03e0 replaces Wine reflection with vkd3d reflection. This is a candidate comparison, not a proven fix to port. - -Searches covered DroidDeck history and a repository fork, FEX, Box64, Winlator, vkd3d-proton, Wine and vkd3d reports, driver trackers, Mesa, and recent component commits. No verified matching general fix was found. - -## Repository audit - -No matching open or draft pull request was found. Closed pull request #1033 concerns remastered presentation timing, a different symptom. Open issues #593, #916 and #218 mention related titles or hardware but do not describe this original-release compiler crash; none should be closed by this investigation. - -`DependencyDetector.kt` lines 155–159 recognize compiler filenames as d3dx9 recommendations, but this does not prove a dependency-installation failure. Existing component placement and architecture regression tests exist in `tools/tests/test_wincomponents.py`. No duplicate helper or title-specific override is warranted by the current evidence. - -## Device evidence - -A Retroid Pocket Duo running application 0.7.1, build pr2426 at 55c9b2b83e30f412c28dce40186359a1917c9d7f, with runtime ubuntu-r1-rc5 was inspected through Steam and the installed manifests. The original release is absent, so the reported crash and DX9 comparison could not be reproduced. No APK was changed. The session was stopped and the application closed after inspection. - -## Next experiment - -Obtain access to the reporter's original GOG installation on a test device, or request controlled reporter runs through the support workflow. Capture the current DX10 baseline, a DX9 run, and a DX10 run with the actual native compiler 33 selected. Preserve explicit user overrides and compare loaded-DLL evidence in each log. - -Trace the two final compiler calls and their HRESULT and blob outputs, then identify what produces the null object before changing runtime code. If native compiler 33 fixes the crash, inspect general redistributable dependency detection and installation rather than adding a title-specific rule. If it does not, compare the newer upstream reflection implementation and instrument the shader-compilation path. - -## Verification boundary - -No runtime-source or test changes were made during the investigation, and no test suite was run. Reproduction and before/after game verification remain unmet. This record must not be advertised as a fix or used to close reports. diff --git a/docs/development/low-memory.md b/docs/development/low-memory.md index 770fc80d11..70916998fc 100644 --- a/docs/development/low-memory.md +++ b/docs/development/low-memory.md @@ -20,6 +20,12 @@ retry delay, up to five minutes. After game exit, speculative launcher readback until the session is under any explicit RAM cap, pressure has subsided, and available RAM can cover twice the launcher's swap while leaving the headroom reserve. Normal demand paging continues while readback is deferred; Steam does not have to wait for the monitor to recover. +The same readback runs while the game is still running once the client has been in front of it +for five seconds (a game stuck on a black screen and left through Steam, or a long stay in the +Steam menu), under the same memory checks and only without an explicit RAM cap. Missing or +unreadable focus data never counts as the client in front. Demand paging +alone left the Steam library and menus blank for about half a minute in that case. The +client is compressed again 20 seconds after the game is back in front. Missing memory counters disable automatic pressure reclaim and speculative readback. Missing PSI alone still permits the `MemAvailable` fallback. No root settings, swap sizes, compression algorithms, Android process priorities or game-specific settings are changed. diff --git a/docs/development/outdoor-lighting-corruption.md b/docs/development/outdoor-lighting-corruption.md deleted file mode 100644 index 582f0e1145..0000000000 --- a/docs/development/outdoor-lighting-corruption.md +++ /dev/null @@ -1,37 +0,0 @@ -# Outdoor lighting corruption investigation - -Status: root cause unknown. The evidence does not yet identify the first incorrect rendering resource, so no production rendering change is justified. - -## Reported behavior and launch environment - -A [public support report](https://discord.com/channels/1552707793247539220/1556195514322780160/1571201861208514720) shows black mountain faces and foliage outdoors while other geometry remains normally lit. The reporter says the corruption disappears indoors. A [later video](https://discord.com/channels/1552707793247539220/1556195514322780160/1571208309103530085) was captured with mods completely disabled. These observations establish the visible symptom but not the failing render pass. - -The supplied session report identifies application 0.7.1 (19) on a Samsung SM-F971U with an Adreno840v2. Automatic driver selection chose DD-Turnip v0.7.0 for both display and Linux rendering. Snapdragon GSR quality was active with 70% sharpness. Driver changes reduced the reporter's observed frequency, but this was not a controlled comparison and GSR remains an uncontrolled variable. - -The session log launches app 489830 through DroidDeck-Proton 11-12.3. Its Gamescope WSI block identifies `SkyrimSE.exe` and DXVK. The reported engine version is insufficient to establish the exact DXVK source revision. No driver error, DXVK resource trace, shader trace, or frame capture identifies a faulty operation. - -## Code and upstream audit - -Existing game environment composition is implemented in `tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env`. Its executable-specific `render_path_defaults` workaround must not be extended to this unresolved symptom. No matching open or merged correction was found in DroidDeck pull requests. - -Issue #2374 concerns an Adreno 650 D3D9 hang and per-game environment ordering. Issue #2167 describes fixed-region tiled corruption on Adreno 850. Neither establishes the same mechanism as this outdoor D3D11 lighting corruption, and neither issue is resolved by this record. - -[Mesa merge request 45918](https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/45918) corrects partial LRZ fast-clear coverage on A8xx hardware. Its per-slice coverage and slice-pitch alignment changes are already present in the source released as [DD-Turnip v0.7.0](https://github.com/Droid-Deck/Drivers/releases/tag/DD-Turnip-v0.7.0). Re-porting that change would not alter the reported driver's behavior. - -[DXVK issue 6023](https://github.com/doitsujin/dxvk/issues/6023) describes black lighting caused by UNORM flag rounding in a different engine. Without shader or resource evidence for this report, applying that workaround globally would be speculative. Searches across Wine, Proton, DXVK, vkd3d-proton, Mesa, FEX, Box64, Winlator, and public fork history did not locate a verified correction matching the supplied evidence. - -## Device comparison - -A Retroid Pocket Duo running 0.7.1 PR #2600 build `5cec6b889b9f9f91a7beee7109a8d0d3de4d4a73` and ubuntu-r1-rc5 was used for a bounded comparison. The affected game was not installed. An installed D3D11 comparison title reached a focused window, but its display remained black while the HUD reported 36–37 FPS. Input did not produce a usable scene, so this attempt neither reproduced the outdoor corruption nor exercised a comparable shadow pass. The session was stopped and the application closed afterward. - -## Required next experiment - -Obtain a runnable affected scene or save and a frame capture from the reported device and build. Record the effective DXVK revision and configuration, driver library hash, and game INI/plugin state. - -At the same camera position, first compare GSR enabled and disabled, then LRZ enabled and disabled, changing one variable at a time and preserving explicit user settings. Inspect the shadow-depth attachment immediately after its clear and draw operations, then inspect the first lighting pass that samples it. If depth is correct, compare the lighting G-buffer inputs and output before presentation. - -Only the first observed incorrect resource can justify selecting a DXVK format or bias correction, a Turnip LRZ or cache correction, a shader-translation correction, or a presentation correction. Until then, per-game overrides, blanket depth-format forcing, and global driver-feature disabling remain inappropriate. - -## Existing validation - -Run `python3 -m unittest tools.tests.test_game_environment tools.tests.test_game_gpu_launchers` through the prescribed test wrapper. All 192 existing tests pass in 4.627 seconds, with two subprocess ResourceWarnings and no failures. Those tests validate existing environment composition only; they are not regression coverage for this rendering symptom. diff --git a/docs/development/steam-game-imports.md b/docs/development/steam-game-imports.md index 2e4a0cc3e7..52d69934fc 100644 --- a/docs/development/steam-game-imports.md +++ b/docs/development/steam-game-imports.md @@ -64,6 +64,17 @@ inherit those routes. Managed shortcuts are replaced; user-created shortcuts and unreadable shortcut files are preserved. Both routes use the existing ARM64 Proton registration. +## Adopting shared library folders + +At every session start, `droiddeck-steam-library` looks through `steamapps/common` of each +added library for non-empty folders no manifest names. A folder whose name is the +`config.installdir` of exactly one playable app in `appcache/appinfo.vdf` (the `game` +type wins over a demo; tools, DLC and ambiguous names are skipped) gets an +`appmanifest_.acf` with `Universe=1`, `StateFlags=4` and no build, so Steam verifies +the existing files and downloads only what differs. Existing manifests are never +rewritten, an app installed in another library is skipped, and only the added library is +written to. Ownership is not read before the client runs; Steam enforces the license. + ## Launcher artwork The installed Steam game scan lists each game's `appcache/librarycache/` diff --git a/tools/fex/patches/0005-gl-thunk-forward-x-errors.patch b/tools/fex/patches/0005-gl-thunk-forward-x-errors.patch new file mode 100644 index 0000000000..c4641ab213 --- /dev/null +++ b/tools/fex/patches/0005-gl-thunk-forward-x-errors.patch @@ -0,0 +1,170 @@ +diff --git a/ThunkLibs/include/common/X11Manager.h b/ThunkLibs/include/common/X11Manager.h +index a0b1f9e..3843a5f 100644 +--- a/ThunkLibs/include/common/X11Manager.h ++++ b/ThunkLibs/include/common/X11Manager.h +@@ -24,7 +24,7 @@ using guest_size_t = size_t; + * guest display/connection. + */ + struct X11Manager { +- std::mutex mutex; ++ std::recursive_mutex mutex; + + // Maps guest connection to intermediary host connection + std::unordered_map connections; +@@ -68,18 +68,25 @@ struct X11Manager { + return it->second; + } + ++ _XDisplay* FindGuestDisplay(const _XDisplay* from) { ++ std::unique_lock lock(mutex); ++ for (auto& [guest, host] : displays) { ++ if (host == from) { ++ return guest; ++ } ++ } ++ return nullptr; ++ } ++ + guest_layout<_XDisplay*> HostToGuestDisplay(const _XDisplay* from) { + if (from == nullptr) { + return {.data = 0}; + } + +- std::unique_lock lock(mutex); +- for (auto& [guest, host] : displays) { +- if (host == from) { +- guest_layout<_XDisplay*> ret; +- ret.data = reinterpret_cast(guest); +- return ret; +- } ++ if (auto guest = FindGuestDisplay(from)) { ++ guest_layout<_XDisplay*> ret; ++ ret.data = reinterpret_cast(guest); ++ return ret; + } + + fprintf(stderr, "ERROR: Could not map host display %p back to guest\n", from); +@@ -106,6 +113,21 @@ struct X11Manager { + return func(Name); + } + ++ static XErrorHandler HostXSetErrorHandler(XErrorHandler Handler) { ++ static auto func = reinterpret_cast(dlsym(GetLibX11(), "XSetErrorHandler")); ++ return func(Handler); ++ } ++ ++ static void HostXLockDisplay(Display* a) { ++ static auto func = reinterpret_cast(dlsym(GetLibX11(), "XLockDisplay")); ++ func(a); ++ } ++ ++ static void HostXUnlockDisplay(Display* a) { ++ static auto func = reinterpret_cast(dlsym(GetLibX11(), "XUnlockDisplay")); ++ func(a); ++ } ++ + static XVisualInfo* HostXGetVisualInfo(Display* a, long b, XVisualInfo* c, int* d) { + static auto func = reinterpret_cast(dlsym(GetLibX11(), "XGetVisualInfo")); + return func(a, b, c, d); +@@ -114,6 +136,7 @@ struct X11Manager { + // NOTE: Struct pointers are replaced by void* to avoid involving data layout conversion here. + int (*GuestXSync)(void*, int) = nullptr; + void* (*GuestXGetVisualInfo)(void*, guest_long, void*, int*) = nullptr; ++ int (*GuestXErrorForward)(void*, guest_long, int, int, int) = nullptr; + + // XDisplayString internally just reads data from _XDisplay's internal struct definition. + // This breaks when data layout is different, so allow reading from a guest context instead. +diff --git a/ThunkLibs/libGL/libGL_Guest.cpp b/ThunkLibs/libGL/libGL_Guest.cpp +index b0eea5b..01eb801 100644 +--- a/ThunkLibs/libGL/libGL_Guest.cpp ++++ b/ThunkLibs/libGL/libGL_Guest.cpp +@@ -28,6 +28,8 @@ $end_info$ + + #include "thunkgen_guest_libGL.inl" + ++#include ++ + typedef void voidFunc(); + + // Maps OpenGL API function names to the address of a guest function which is +@@ -79,11 +81,26 @@ static void* malloc_wrapper(size_t size) { + return malloc(size); + } + ++static int ForwardXError(Display* display, long resourceid, int error_code, int request_code, int minor_code) { ++ xError error {}; ++ error.type = X_Error; ++ error.errorCode = error_code; ++ error.resourceID = resourceid; ++ error.majorCode = request_code; ++ error.minorCode = minor_code; ++ LockDisplay(display); ++ error.sequenceNumber = display->request; ++ int result = _XError(display, &error); ++ UnlockDisplay(display); ++ return result; ++} ++ + static void OnInit() { + fexfn_pack_GL_SetGuestMalloc((uintptr_t)malloc_wrapper, (uintptr_t)CallbackUnpack::Unpack); + fexfn_pack_GL_SetGuestXSync((uintptr_t)XSync, (uintptr_t)CallbackUnpack::Unpack); + fexfn_pack_GL_SetGuestXGetVisualInfo((uintptr_t)XGetVisualInfo, (uintptr_t)CallbackUnpack::Unpack); + fexfn_pack_GL_SetGuestXDisplayString((uintptr_t)XDisplayString, (uintptr_t)CallbackUnpack::Unpack); ++ fexfn_pack_GL_SetGuestXErrorForward((uintptr_t)ForwardXError, (uintptr_t)CallbackUnpack::Unpack); + } + + // libGL.so must pull in libX11.so as a dependency. Referencing some libX11 +diff --git a/ThunkLibs/libGL/libGL_Host.cpp b/ThunkLibs/libGL/libGL_Host.cpp +index dd3cec4..84efe41 100644 +--- a/ThunkLibs/libGL/libGL_Host.cpp ++++ b/ThunkLibs/libGL/libGL_Host.cpp +@@ -66,6 +66,28 @@ static void fexfn_impl_libGL_GL_SetGuestXDisplayString(uintptr_t GuestTarget, ui + MakeHostTrampolineForGuestFunctionAt(GuestTarget, GuestUnpacker, &x11_manager.GuestXDisplayString); + } + ++static XErrorHandler HostPreviousXErrorHandler = nullptr; ++ ++static int HostXErrorHandler(Display* HostDisplay, XErrorEvent* Event) { ++ auto GuestDisplay = x11_manager.FindGuestDisplay(HostDisplay); ++ if (!GuestDisplay || !x11_manager.GuestXErrorForward) { ++ return HostPreviousXErrorHandler ? HostPreviousXErrorHandler(HostDisplay, Event) : 0; ++ } ++ x11_manager.HostXUnlockDisplay(HostDisplay); ++ int Result = x11_manager.GuestXErrorForward(GuestDisplay, static_cast(Event->resourceid), Event->error_code, ++ Event->request_code, Event->minor_code); ++ x11_manager.HostXLockDisplay(HostDisplay); ++ return Result; ++} ++ ++static void fexfn_impl_libGL_GL_SetGuestXErrorForward(uintptr_t GuestTarget, uintptr_t GuestUnpacker) { ++ MakeHostTrampolineForGuestFunctionAt(GuestTarget, GuestUnpacker, &x11_manager.GuestXErrorForward); ++ auto Previous = x11_manager.HostXSetErrorHandler(HostXErrorHandler); ++ if (Previous != HostXErrorHandler) { ++ HostPreviousXErrorHandler = Previous; ++ } ++} ++ + #include "thunkgen_host_libGL.inl" + + auto fexfn_impl_libGL_glXGetProcAddress(const GLubyte* name) -> void (*)() { +diff --git a/ThunkLibs/libGL/libGL_interface.cpp b/ThunkLibs/libGL/libGL_interface.cpp +index 04a2d2b..b769cda 100644 +--- a/ThunkLibs/libGL/libGL_interface.cpp ++++ b/ThunkLibs/libGL/libGL_interface.cpp +@@ -26,6 +26,7 @@ void GL_SetGuestMalloc(uintptr_t, uintptr_t); + void GL_SetGuestXSync(uintptr_t, uintptr_t); + void GL_SetGuestXGetVisualInfo(uintptr_t, uintptr_t); + void GL_SetGuestXDisplayString(uintptr_t, uintptr_t); ++void GL_SetGuestXErrorForward(uintptr_t, uintptr_t); + template<> + struct fex_gen_config : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {}; + template<> +@@ -34,6 +35,8 @@ template<> + struct fex_gen_config : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {}; + template<> + struct fex_gen_config : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {}; ++template<> ++struct fex_gen_config : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {}; + + template + struct fex_gen_type {}; diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent index 5ae8031e68..eb860e3222 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent @@ -391,18 +391,26 @@ class FocusWatcher(threading.Thread): x.close() except (OSError, AgentError) as e: log("focus snapshot failed: %s" % e) + self.publish({}) time.sleep(2) continue if tag_game_windows(snap): self.changed.set() continue - body = {k: v for k, v in snap.items() if k != "t"} - if body == self.last: - continue - self.last = body - self.seq += 1 - snap["seq"] = self.seq - write_json(self.path, snap) + self.publish(snap) + + def publish(self, snap): + body = {k: v for k, v in snap.items() if k != "t"} + if body == self.last: + return + try: + write_json(self.path, dict(snap, seq=self.seq + 1)) + except OSError as e: + log("focus publication failed: %s" % e) + self.changed.set() + return + self.seq += 1 + self.last = body def listen(self): while True: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks index 5cbf57b4aa..411a9c6bda 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks @@ -67,7 +67,25 @@ def place_uri(uri): return uri -def update_places(path, libraries): +def removable_volumes(): + listing = os.environ.get("BL_DESKTOP_VOLUMES") + if not listing: + return {} + volumes = {} + for entry in json.loads(Path(listing).read_text()): + path = Path(entry["path"]) + if not path.is_absolute(): + continue + try: + with os.scandir(path): + pass + except OSError: + continue + volumes[path.as_uri()] = " ".join(str(entry["label"]).split()) or path.name + return volumes + + +def update_places(path, libraries, mark=MARK, icon_name="steam", id_prefix="droiddeck-steam-"): if path.is_file(): parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True, insert_pis=True)) root = ET.fromstring(path.read_bytes(), parser=parser) @@ -80,10 +98,10 @@ def update_places(path, libraries): before = ET.tostring(root) seen = set() personal = {place_uri(b.get("href")) for b in root.findall("bookmark") - if b.find("info/metadata[@owner='" + KDE_OWNER + "']/" + MARK) is None} + if b.find("info/metadata[@owner='" + KDE_OWNER + "']/" + mark) is None} for bookmark in root.findall("bookmark"): metadata = bookmark.find("info/metadata[@owner='" + KDE_OWNER + "']") - if metadata is None or metadata.find(MARK) is None: + if metadata is None or metadata.find(mark) is None: continue uri = place_uri(bookmark.get("href")) if uri not in libraries or uri in seen or uri in personal: @@ -101,10 +119,10 @@ def update_places(path, libraries): ET.SubElement(bookmark, "title").text = label info = ET.SubElement(bookmark, "info") icon = ET.SubElement(info, "metadata", {"owner": "http://freedesktop.org"}) - ET.SubElement(icon, "{" + ICON_NS + "}icon", {"name": "steam"}) + ET.SubElement(icon, "{" + ICON_NS + "}icon", {"name": icon_name}) metadata = ET.SubElement(info, "metadata", {"owner": KDE_OWNER}) - ET.SubElement(metadata, "ID").text = "droiddeck-steam-" + hashlib.sha256(uri.encode()).hexdigest()[:16] - ET.SubElement(metadata, MARK).text = "true" + ET.SubElement(metadata, "ID").text = id_prefix + hashlib.sha256(uri.encode()).hexdigest()[:16] + ET.SubElement(metadata, mark).text = "true" ET.SubElement(metadata, "isSystemItem").text = "false" if ET.tostring(root) != before: atomic_write(path, ET.tostring(root, encoding="unicode", xml_declaration=True)) @@ -154,7 +172,9 @@ def main(): available = bool(label) and (LIBRARY / "steamapps").is_dir() update_bookmark(bookmarks_file(home, config), label if available else None) data = Path(os.environ.get("XDG_DATA_HOME") or home / ".local/share") - update_places(data / "user-places.xbel", steam_libraries(home, data)) + places = data / "user-places.xbel" + update_places(places, steam_libraries(home, data)) + update_places(places, removable_volumes(), "DroidDeckRemovableVolume", "drive-removable-media", "droiddeck-volume-") if __name__ == "__main__": diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex index af04761346..742cabc91a 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex @@ -38,7 +38,7 @@ RUNTIMES = {SNIPER_APPID: ("sniper_platform_", "Steam Linux Runtime 3.0 (sniper" SLR4_APPID: ("steamrt4_platform_", "Steam Linux Runtime 4.0 (steamrt4")} MARKER = ".droiddeck-fex" LAYOUT = 1 -ROOTFS_LAYOUT = 4 +ROOTFS_LAYOUT = 10 BLOB_DIRS = re.compile(r"^(?:\.ref|[0-9a-f]{2})$") ROOTFS_LIBRARY_DIRS = ("lib", "lib64") ARCH_DIRS = ("x86_64-linux-gnu", "i386-linux-gnu") @@ -49,7 +49,15 @@ PROVIDED = frozenset(( "libnss_compat.so.2", "libnss_dns.so.2", "libnss_files.so.2", "libnss_hesiod.so.2", "libthread_db.so.1", "libmemusage.so", "libpcprofile.so", "libc_malloc_debug.so.0", "gconv", "libstdc++.so.6", "libgcc_s.so.1", "libssl.so.3", "libcrypto.so.3", + "libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1", "libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1", + "libwayland-client.so.0", "libwayland-egl.so.1", "libwayland-server.so.0", "libffi.so.8", + "libgbm.so.1", "libdrm.so.2", "libexpat.so.1", )) +PROVIDED_NEEDS = { + "libwayland-client.so.0": ("libffi.so.8",), + "libwayland-server.so.0": ("libffi.so.8",), + "libgbm.so.1": ("libdrm.so.2", "libexpat.so.1"), +} GLIBC_BUILD = re.compile(r"^(?:ld|lib[A-Za-z_]+)-2\.[0-9]+\.so$|^libSegFault\.so$") GUEST_LIBDIRS = (("x86_64", "lib/x86_64-linux-gnu"), ("i386", "lib/i386-linux-gnu")) PRELOAD_NAMES = ("libblsession.so", "libfakeinput.so") @@ -343,10 +351,14 @@ def stays_in_libraries(root, target, link): def mirror(source, provider, name, target, root): - if provider and name in PROVIDED and os.path.lexists(os.path.join(provider, name)): + usable_provider = provider and all(os.path.exists(os.path.join(provider, needed)) + for needed in (name,) + PROVIDED_NEEDS.get(name, ())) + if name in PROVIDED and usable_provider: clone(os.path.join(provider, name), os.path.join(target, name)) return path = os.path.join(source, name) + if not os.path.lexists(path): + return link = os.readlink(path) if os.path.islink(path) else None if link and GLIBC_BUILD.match(os.path.basename(link)): if name not in INTERPRETERS: @@ -365,6 +377,16 @@ def build_rootfs(base, provider): rootfs = os.path.join(STATE, "rootfs") stamp = "%d\n%s\n%s%s\n%s" % (ROOTFS_LAYOUT, os.path.realpath(base), read_text(os.path.join(base_files, MARKER)) or "", os.path.realpath(provider), read_text(os.path.join(provider_files, MARKER)) or "") + for top in ("lib", "lib64"): + for arch in ARCH_DIRS: + for name in sorted(PROVIDED): + path = os.path.join(provider_files, top, arch, name) + try: + info = os.stat(path) + stamp += "\n%s %s %d %d %d %d" % (path, os.path.realpath(path), info.st_ino, info.st_size, + info.st_mtime_ns, info.st_ctime_ns) + except OSError: + stamp += "\n%s missing" % path if read_text(os.path.join(rootfs, MARKER)) == stamp: return False for entry in os.listdir(STATE): @@ -384,7 +406,7 @@ def build_rootfs(base, provider): if entry in ARCH_DIRS and os.path.isdir(path) and not os.path.islink(path): provided = os.path.join(provider_files, top, entry) os.makedirs(os.path.join(tmp, top, entry)) - for name in set(os.listdir(path)) | {name for name in PROVIDED if os.path.lexists(os.path.join(provided, name))}: + for name in set(os.listdir(path)) | {name for name in PROVIDED if os.path.exists(os.path.join(provided, name))}: mirror(path, provided, name, os.path.join(tmp, top, entry), tmp) else: mirror(source, None, entry, os.path.join(tmp, top), tmp) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index 4d36d446d0..82772f80b0 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -1104,7 +1104,7 @@ case $mode in local id id=$(sed -n 's/.*"focusedApp"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' \ "$BL_LAUNCH_DIR/agent/focus.json" 2>/dev/null | head -1) - [ -n "$id" ] || return "${1:-1}" + [ -n "$id" ] || return "${1:-2}" case " ${_bl_apps-} " in *" $id "*) return 0 ;; esac @@ -1122,7 +1122,7 @@ case $mode in } _bl_since=-1 _bl_since_apps= _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30 _bl_pressure_at=-1 _bl_pressure_backoff=30 _bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0 _bl_tier_back=0 _bl_tier_targets=() _bl_tier_swaps=() _bl_tier_starts=() - _bl_client_pending=0 _bl_client_reserve=0 _bl_client_targets=() + _bl_client_pending=0 _bl_client_reserve=0 _bl_client_targets=() _bl_away= _bl_sample_at= _bl_sample_available=0 _bl_sample_gpu=0 _bl_sample_unevictable=0 _bl_sample_shmem=0 while kill -0 $$ 2>/dev/null; do bl_zram_scan @@ -1155,7 +1155,10 @@ case $mode in _bl_preserved_growth=$_bl_growth _bl_preserved_fall=$_bl_fall bl_session_pressure bl_client_pressure_finish - if [ "$_bl_game" = 1 ] && bl_game_focused; then + _bl_focus=1 + [ "$_bl_game" = 1 ] && { bl_game_focused && _bl_focus=0 || _bl_focus=$?; } + if [ "$_bl_game" = 1 ] && [ "$_bl_focus" = 0 ]; then + _bl_away= if [ "$_bl_since" -lt 0 ] || [ "$_bl_since_apps" != "$_bl_apps" ]; then _bl_since=$SECONDS _bl_since_apps=$_bl_apps fi @@ -1165,15 +1168,31 @@ case $mode in _bl_packed=$SECONDS fi elif [ "$_bl_game" != 1 ]; then + _bl_away= if [ "$_bl_packed" -ge 0 ]; then _bl_unpack=1 fi _bl_since=-1 _bl_packed=-1 _bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0 _bl_tier_targets=() _bl_tier_swaps=() _bl_tier_starts=() else _bl_since=-1 + if [ "$_bl_focus" = 1 ]; then + [ -n "${_bl_away-}" ] || _bl_away=$SECONDS + else + _bl_away= + fi + if [ "$_bl_packed" -ge 0 ]; then + _bl_unpack=1 + fi fi - if [ "$_bl_unpack" = 1 ] && [ "$_bl_game" = 0 ] && ! bl_over_cap && bl_client_can_readback; then - bl_zram_send 0 "memory recovered, reading the client back" client + if [ "$_bl_unpack" = 1 ] && + { [ "$_bl_game" = 0 ] || { [ "${_bl_ram_cap:-0}" = 0 ] && [ -n "${_bl_away-}" ] && [ $((SECONDS - _bl_away)) -ge 5 ]; }; } && + ! bl_over_cap && bl_client_can_readback; then + if [ "$_bl_game" = 0 ]; then + bl_zram_send 0 "memory recovered, reading the client back" client + else + bl_zram_send 0 "the client is in front of the game, reading it back" client + _bl_packed=-1 + fi _bl_unpack=0 fi bl_watch_nap diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games index ac8213d41e..e8e2ff4e61 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games @@ -1,9 +1,11 @@ #!/usr/bin/env python3 import ctypes as C +import functools import json import os from pathlib import Path import re +import runpy import shlex import subprocess import sys @@ -445,18 +447,22 @@ def park(steamapps): print(f"droiddeck-steam-games: {appid} is not here this session; its install is set aside until it is") +@functools.lru_cache(maxsize=1) +def compatibility(): + return runpy.run_path(os.path.join(os.path.dirname(os.path.abspath(__file__)), "steam-compatibility")) + + def seed_install(steam_root, game, appid): steamapps = Path(steam_root) / "steamapps" common = steamapps / "common" name = f"DroidDeck-{appid}" target = common / name source = Path(game["folder"]) - title = game["name"].replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ") - minimal = ('"AppState"\n{\n' + f' "appid" "{appid}"\n "Universe" "1"\n "name" "{title}"\n' - + f' "StateFlags" "4"\n "installdir" "{name}"\n' + '}\n') + manifest_text = compatibility()["manifest_text"] + minimal = manifest_text(appid, game["name"], name) legacy = minimal.replace(' "Universe" "1"\n', '') # Steam checks every file of an import with no build before updating it, from scratch each time it is interrupted. - bare = minimal[:-2] + ' "AutoUpdateBehavior" "1"\n}\n' + bare = manifest_text(appid, game["name"], name, True) build = installed_build(source, appid, name) if build is None: content = bare diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-library b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-library index 5577e1aad7..2aeac02bb3 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-library +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-library @@ -2,8 +2,10 @@ import json import os import re +import runpy import sys +BIN_DIR = os.path.dirname(os.path.abspath(__file__)) LIBRARIES = (("/mnt/droiddeck-sd", os.environ.get("BL_LIBRARY_LABEL", "SD Card")),) MAIN_LABEL = "Internal Storage" @@ -50,6 +52,77 @@ def register(steam_root, library, label): return len(apps) +def installdirs(libraries): + found = set() + for library in libraries: + steamapps = os.path.join(library, "steamapps") + try: + names = os.listdir(steamapps) + except OSError: + continue + for name in names: + if not re.fullmatch(r"appmanifest_\d+\.acf", name): + continue + try: + with open(os.path.join(steamapps, name), encoding="utf-8", errors="replace") as f: + m = re.search(r'"installdir"\s+"([^"]*)"', f.read(), re.I) + except OSError: + continue + if m: + found.add(m.group(1)) + return found + + +def populated(path): + try: + with os.scandir(path) as entries: + return next(entries, None) is not None + except OSError: + return False + + +def adoptable(library, known): + common = os.path.join(library, "steamapps", "common") + try: + names = sorted(os.listdir(common)) + except OSError: + return [] + return [n for n in names if n not in known and not n.startswith(".") + and os.path.isdir(os.path.join(common, n)) and populated(os.path.join(common, n))] + + +def adopt(steam_root, library): + compat = runpy.run_path(os.path.join(BIN_DIR, "steam-compatibility")) + known = compat["libraries"](steam_root) + folders = adoptable(library, installdirs(known + [library])) + if not folders: + return 0 + entries = compat["appinfo_entries"](os.path.join(steam_root, "appcache", "appinfo.vdf")) + by_dir = {} + for app, info in entries.items(): + if app not in compat["NOT_GAMES"] and info["type"] in compat["PLAYABLE_TYPES"] and info["installdir"]: + by_dir.setdefault(info["installdir"], []).append((app, info)) + steamapps = os.path.join(library, "steamapps") + adopted = 0 + for folder in folders: + matches = by_dir.get(folder, []) + games = [m for m in matches if m[1]["type"] == "game"] or matches + if len(games) != 1: + continue + app, info = games[0] + if any(os.path.isfile(os.path.join(root, "steamapps", "appmanifest_%s.acf" % app)) + for root in known + [library]): + continue + try: + with open(os.path.join(steamapps, "appmanifest_%s.acf" % app), "x", encoding="utf-8") as f: + f.write(compat["manifest_text"](app, info["name"] or folder, folder, True)) + except OSError: + continue + adopted += 1 + print("droiddeck-steam-library: adopted %s as app %s in %s" % (folder, app, library)) + return adopted + + RETIRED = ("/mnt/bannerlator",) RENAMED = (("/mnt/bannerlator-sd", "/mnt/droiddeck-sd"),) @@ -176,6 +249,7 @@ def main(): managed = libraries is not None for library, label in libraries if managed else LIBRARIES: if os.path.isdir(os.path.join(library, "steamapps")): + adopt(steam_root, library) register(steam_root, library, label) relabel(steam_root, library, label) else: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch index d4cb905f4c..98b533c79d 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch @@ -7,6 +7,7 @@ import os import re import shlex import shutil +import stat import sys import time import subprocess @@ -291,6 +292,8 @@ def exited(argv, code=0): compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH") if compat_data: (Path(compat_data) / "pfx" / ROCKSTAR_FOLDER / "launch.json").unlink(missing_ok=True) + for line in rockstar_launcher_log(compat_data): + log("rockstar launcher: " + line) return 0 if found is not None and str(found[1].get("store")) == "epic" and os.environ.get(EPIC_HANDLED) != "1" \ and os.access(EPIC_CLIENT, os.X_OK): @@ -320,6 +323,29 @@ ROCKSTAR_TITLES = {"gta3": "Grand Theft Auto III", "gtavc": "Grand Theft Auto: V "gta4": "Grand Theft Auto IV", "lanoire": "LANoireMTL"} +def rockstar_launcher_log(compat_data, limit=65536): + pfx = Path(compat_data) / "pfx" + target = pfx / ROCKSTAR_FOLDER + if not target.resolve().is_relative_to(pfx.resolve()): + return [] + path = target / "launcher.log" + try: + descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + except OSError: + return [] + try: + if not stat.S_ISREG(os.fstat(descriptor).st_mode): + return [] + with os.fdopen(descriptor, "rb", closefd=False) as source: + data = source.read(limit) + path.unlink(missing_ok=True) + except OSError: + return [] + finally: + os.close(descriptor) + return [line.strip() for line in data.decode("utf-8", "replace").splitlines() if line.strip()] + + def rockstar_sdk(folder, sidecar): if str(sidecar.get("id")) in ("gta4", "lanoire"): return True @@ -464,6 +490,7 @@ def prepare_rockstar(folder, sidecar, compat_data, launch_dir, proton="", ask_ap return "invalid-service-path" config = target / "launch.json" config.unlink(missing_ok=True) + (target / "launcher.log").unlink(missing_ok=True) legacy = str(sidecar.get("id")) in ROCKSTAR_TITLES sdk = rockstar_sdk(folder, sidecar) title = ROCKSTAR_TITLES.get(str(sidecar.get("id"))) diff --git a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility index cf616c86fc..52a589d21d 100755 --- a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility +++ b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility @@ -86,6 +86,7 @@ bl_run() { set -- /usr/local/bin/droiddeck-steamvr-game "$@" fi if [ -n "${BL_STORE_EXIT:-}" ]; then + trap : INT TERM HUP "$@" rc=$? /usr/local/bin/droiddeck-store-launch --exited --code "$rc" "${BL_STORE_ARGS[@]}" || true @@ -892,7 +893,10 @@ def appinfo_entries(path, wanted=None): deck = common.get("steam_deck_compatibility") configuration = deck.get("configuration") if isinstance(deck, dict) else None recommended = configuration.get("recommended_runtime", "") if isinstance(configuration, dict) else "" + config = info.get("config") if isinstance(info.get("config"), dict) else {} entry = { + "name": str(common.get("name", "")), + "installdir": str(config.get("installdir", "")), "oslist": {part.strip().lower() for part in str(common.get("oslist", "")).split(",") if part.strip()}, "osarch": str(common.get("osarch", "")).lower(), "type": str(common.get("type", "")).lower(), @@ -959,6 +963,13 @@ def native_targets(steam_root, apps): return targets +def manifest_text(appid, name, installdir, bare=False): + title = name.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ") + text = ('"AppState"\n{\n' + f' "appid" "{appid}"\n "Universe" "1"\n "name" "{title}"\n' + + f' "StateFlags" "4"\n "installdir" "{installdir}"\n' + '}\n') + return text[:-2] + ' "AutoUpdateBehavior" "1"\n}\n' if bare else text + + def app_manifest(steam_root, app): for library in libraries(steam_root): try: diff --git a/tools/linuxfs/preload/zram.c b/tools/linuxfs/preload/zram.c index af62c29413..e271668bea 100644 --- a/tools/linuxfs/preload/zram.c +++ b/tools/linuxfs/preload/zram.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -20,11 +21,14 @@ #endif #define ZR_SWAPPED (1ULL << 62) #define ZR_BATCH 512 +#define ZR_FUTEX_WAIT 0 +#define ZR_FUTEX_WAKE 1 static long (*zr_sys)(long, ...); static unsigned long zr_page; static int zr_busy; static int zr_pending; +static int zr_worker; static char zr_maps[8192]; static uint64_t zr_entries[ZR_BATCH]; static struct iovec zr_iov[ZR_BATCH]; @@ -143,19 +147,36 @@ static void zr_ack(int done) { zr_sys(SYS_close, fd); } +static void zr_request(void) { + int mode = zr_mode(); + if (mode == 1) zr_ack(0); + if (mode >= 0) zr_walk(mode); + if (mode == 1) zr_ack(1); +} + +static void *zr_worker_main(void *unused) { + (void)unused; + prctl(PR_SET_NAME, "zr-worker", 0, 0, 0); + for (;;) { + while (!__atomic_exchange_n(&zr_pending, 0, __ATOMIC_SEQ_CST)) + zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAIT, 0, NULL, NULL, 0); + zr_request(); + } + return NULL; +} + static void zr_handler(int sig, siginfo_t *info, void *context) { (void)sig; (void)context; if (info == NULL || info->si_code != SI_USER) return; int saved = errno; __atomic_store_n(&zr_pending, 1, __ATOMIC_SEQ_CST); - while (__atomic_load_n(&zr_pending, __ATOMIC_SEQ_CST) - && !__atomic_exchange_n(&zr_busy, 1, __ATOMIC_SEQ_CST)) { + if (__atomic_load_n(&zr_worker, __ATOMIC_ACQUIRE)) { + zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAKE, 1, NULL, NULL, 0); + } else while (__atomic_load_n(&zr_pending, __ATOMIC_SEQ_CST) + && !__atomic_exchange_n(&zr_busy, 1, __ATOMIC_SEQ_CST)) { __atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST); - int mode = zr_mode(); - if (mode == 1) zr_ack(0); - if (mode >= 0) zr_walk(mode); - if (mode == 1) zr_ack(1); + zr_request(); __atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST); } errno = saved; @@ -164,6 +185,7 @@ static void zr_handler(int sig, siginfo_t *info, void *context) { static void zr_child(void) { __atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST); __atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST); + __atomic_store_n(&zr_worker, 0, __ATOMIC_RELEASE); } __attribute__((constructor)) static void zr_init(void) { @@ -184,5 +206,21 @@ __attribute__((constructor)) static void zr_init(void) { sa.sa_sigaction = zr_handler; sa.sa_flags = SA_SIGINFO | SA_RESTART; sigemptyset(&sa.sa_mask); - if (sigaction(SIGURG, &sa, NULL) == 0) pthread_atfork(NULL, NULL, zr_child); + if (sigaction(SIGURG, &sa, NULL) == 0) { + pthread_atfork(NULL, NULL, zr_child); + pthread_attr_t attr; + if (pthread_attr_init(&attr) == 0) { + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + pthread_t thread; + sigset_t blocked; + sigset_t previous; + if (sigfillset(&blocked) == 0 && + pthread_sigmask(SIG_SETMASK, &blocked, &previous) == 0) { + if (pthread_create(&thread, &attr, zr_worker_main, NULL) == 0) + __atomic_store_n(&zr_worker, 1, __ATOMIC_RELEASE); + pthread_sigmask(SIG_SETMASK, &previous, NULL); + } + pthread_attr_destroy(&attr); + } + } } diff --git a/tools/rockstar-launcher/README.md b/tools/rockstar-launcher/README.md index 62ae5642e6..020e21dcb7 100644 --- a/tools/rockstar-launcher/README.md +++ b/tools/rockstar-launcher/README.md @@ -6,7 +6,7 @@ The handoff is mode 0600, expires after 90 seconds and is deleted before startin GTA III, Vice City and San Andreas use body-length MTLX replies. GTA IV and L.A. Noire use total-length, terminated replies. Titles with installed Social Club metadata or SDK binaries use the SDK IPC adapter, including user-info, login, ticket, initialization and authorized title-state synchronization. The title metadata supplies the ROS identity and principal executable; it is checked against Rockstar's catalog before title authorization. Other titles retain Play and Steam shortcuts and attempt the normal executable launch path. -The SDK runtime is extracted from the game's own Social-Club-Setup.exe when present. Architecture-specific payloads are staged into the prefix, archive paths and sizes are checked, interrupted copies are retried, and both registry views are registered. The helper discovers launcher identity pipe names in the game executable and answers bounded INIT challenges from the launched process. No vendor executables or runtime files are bundled with this tool. SDK initialization has a 90-second deadline. SDK wire tests and fixture clients do not establish gameplay compatibility for every title; per-title ROS ticket exchange and secondary SDK channels remain unverified. +The SDK runtime is extracted from the game's own Social-Club-Setup.exe when present. Architecture-specific payloads are staged into the prefix, archive paths and sizes are checked, interrupted copies are retried, and both registry views are registered. The helper discovers launcher identity pipe names in the game executable and the executables beside it, because protected game executables resolve that name only at run time, and answers bounded INIT challenges from the launched process. No vendor executables or runtime files are bundled with this tool. SDK initialization has a 90-second deadline. SDK wire tests and fixture clients do not establish gameplay compatibility for every title; per-title ROS ticket exchange and secondary SDK channels remain unverified. GTA III defaults to full x87 precision for FEX before Wine starts, because reduced precision crashed new-game initialization on the test device. San Andreas defaults to WineD3D, because DXVK intermittently corrupted its textures; full precision and conservative memory ordering did not prevent that corruption. These defaults use DroidDeck's per-game settings and preserve explicit per-game overrides. diff --git a/tools/rockstar-launcher/src/identity.rs b/tools/rockstar-launcher/src/identity.rs index 795d56da1a..b059787b0d 100644 --- a/tools/rockstar-launcher/src/identity.rs +++ b/tools/rockstar-launcher/src/identity.rs @@ -1,5 +1,7 @@ -use std::collections::BTreeSet; +use std::collections::BTreeMap; +use std::fs::{self, File}; use std::io::{self, Read}; +use std::path::{Path, PathBuf}; const LIMIT: usize = 4096; @@ -10,7 +12,13 @@ fn invalid() -> io::Error { ) } -fn collect(bytes: &[u8], names: &mut BTreeSet) { +type Names = BTreeMap; + +const SCAN_LIMIT: u64 = 256 * 1024 * 1024; +const NAME_LIMIT: usize = 4; +const SIBLING_LIMIT: usize = 32; + +fn collect(bytes: &[u8], names: &mut Names) { let prefix = br"\\.\pipe\"; for (index, window) in bytes.windows(prefix.len()).enumerate() { if window != prefix { @@ -28,41 +36,95 @@ fn collect(bytes: &[u8], names: &mut BTreeSet) { { let name = std::str::from_utf8(name).unwrap(); if name.ends_with("LauncherPipe") || name.ends_with("Launcher_Pipe") { - names.insert(name.to_owned()); + names + .entry(name.to_ascii_lowercase()) + .or_insert_with(|| name.to_owned()); } } } } -pub fn pipe_names(reader: &mut impl Read) -> io::Result> { - let mut names = BTreeSet::new(); +pub fn title_pipe_names(exe: &Path) -> io::Result> { + discover(exe, SCAN_LIMIT) +} + +fn discover(exe: &Path, limit: u64) -> io::Result> { + let mut names = Names::new(); + let mut principal = limit; + scan(&mut File::open(exe)?, &mut names, &mut principal)?; + let mut extra = Names::new(); + let mut budget = limit; + for path in siblings(exe) { + if extra.len() >= NAME_LIMIT || budget == 0 { + break; + } + let Ok(mut file) = File::open(&path) else { + continue; + }; + if !file + .metadata() + .is_ok_and(|metadata| metadata.len() <= budget) + { + continue; + } + let mut own = Names::new(); + if scan(&mut file, &mut own, &mut budget).is_err() { + continue; + } + for (key, name) in own { + if extra.len() < NAME_LIMIT && !names.contains_key(&key) { + extra.entry(key).or_insert(name); + } + } + } + names.append(&mut extra); + Ok(names.into_values().collect()) +} + +fn siblings(exe: &Path) -> Vec { + let Some(entries) = exe.parent().and_then(|folder| fs::read_dir(folder).ok()) else { + return Vec::new(); + }; + let mut paths: Vec<_> = entries + .flatten() + .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_file())) + .map(|entry| entry.path()) + .filter(|path| { + path != exe + && path + .extension() + .is_some_and(|extension| extension.eq_ignore_ascii_case("exe")) + }) + .collect(); + paths.sort(); + paths.truncate(SIBLING_LIMIT); + paths +} + +fn scan(reader: &mut impl Read, names: &mut Names, budget: &mut u64) -> io::Result<()> { let mut carry = Vec::new(); let mut chunk = [0; 65536]; - let mut total = 0usize; loop { let count = reader.read(&mut chunk)?; if count == 0 { break; } - total += count; - if total > 256 * 1024 * 1024 { - return Err(invalid()); - } + *budget = budget.checked_sub(count as u64).ok_or_else(invalid)?; carry.extend_from_slice(&chunk[..count]); - collect(&carry, &mut names); + collect(&carry, names); for offset in 0..2 { let ascii: Vec<_> = carry[offset..] .chunks_exact(2) .map(|pair| if pair[1] == 0 { pair[0] } else { 0 }) .collect(); - collect(&ascii, &mut names); + collect(&ascii, names); } - if names.len() > 4 { + if names.len() > NAME_LIMIT { return Err(invalid()); } carry.drain(..carry.len().saturating_sub(256)); } - Ok(names.into_iter().collect()) + Ok(()) } pub fn exchange(reader: &mut impl Read) -> io::Result> { @@ -134,12 +196,165 @@ mod tests { } bytes.extend_from_slice(br"\\.\pipe\..\outsideLauncherPipe"); bytes.push(0); + let mut names = Names::new(); + scan(&mut Cursor::new(bytes), &mut names, &mut SCAN_LIMIT.clone()).unwrap(); assert_eq!( - pipe_names(&mut Cursor::new(bytes)).unwrap(), + names.into_values().collect::>(), ["GameLauncherPipe", "OtherLauncher_Pipe"] ); } + fn folder(name: &str) -> std::path::PathBuf { + let path = + std::env::temp_dir().join(format!("droiddeck-identity-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir(&path).unwrap(); + path + } + + #[test] + fn title_names_include_sibling_launcher_executables() { + let root = folder("siblings"); + let game = root.join("Game.exe"); + fs::write(&game, b"MZ obfuscated").unwrap(); + fs::write( + root.join("TitleLauncher.exe"), + [br"MZ \\.\pipe\TitleLauncher_Pipe".as_slice(), b"\0"].concat(), + ) + .unwrap(); + fs::write( + root.join("Data.dat"), + [br"\\.\pipe\DataLauncher_Pipe".as_slice(), b"\0"].concat(), + ) + .unwrap(); + fs::create_dir(root.join("Folder.exe")).unwrap(); + let names = title_pipe_names(&game).unwrap(); + fs::remove_dir_all(&root).unwrap(); + assert_eq!(names, ["TitleLauncher_Pipe"]); + } + + fn executable(path: &Path, names: &[&str]) { + let mut bytes = b"MZ ".to_vec(); + for name in names { + bytes.extend_from_slice(br"\\.\pipe\"); + bytes.extend_from_slice(name.as_bytes()); + bytes.push(0); + } + fs::write(path, bytes).unwrap(); + } + + #[test] + fn title_names_keep_the_game_executable_names_and_limits() { + let root = folder("principal"); + let game = root.join("Game.exe"); + executable(&game, &["GameLauncherPipe"]); + fs::write(root.join("Tool.exe"), b"MZ plain").unwrap(); + assert_eq!(title_pipe_names(&game).unwrap(), ["GameLauncherPipe"]); + for index in 0..40 { + fs::write(root.join(format!("Extra{index:02}.exe")), b"MZ").unwrap(); + } + executable(&root.join("Zz.exe"), &["LateLauncher_Pipe"]); + let crowded = title_pipe_names(&game); + executable( + &game, + &[ + "ALauncherPipe", + "BLauncherPipe", + "CLauncherPipe", + "DLauncherPipe", + "ELauncherPipe", + ], + ); + let overfull = title_pipe_names(&game); + fs::remove_dir_all(&root).unwrap(); + assert_eq!(crowded.unwrap(), ["GameLauncherPipe"]); + assert!(overfull.is_err()); + } + + #[test] + fn title_names_skip_siblings_that_cannot_be_scanned() { + use std::os::unix::fs::PermissionsExt; + let root = folder("unscannable"); + let game = root.join("Game.exe"); + executable(&game, &["GameLauncherPipe"]); + let locked = root.join("Locked.exe"); + executable(&locked, &["LockedLauncher_Pipe"]); + fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap(); + let locked_open = File::open(&locked).is_ok(); + File::create(root.join("Huge.exe")) + .unwrap() + .set_len(SCAN_LIMIT + 1) + .unwrap(); + executable( + &root.join("Noisy.exe"), + &[ + "NALauncherPipe", + "NBLauncherPipe", + "NCLauncherPipe", + "NDLauncherPipe", + "NELauncherPipe", + ], + ); + let names = title_pipe_names(&game); + fs::remove_dir_all(&root).unwrap(); + let mut expected = vec!["GameLauncherPipe".to_owned()]; + if locked_open { + expected.push("LockedLauncher_Pipe".to_owned()); + } + assert_eq!(names.unwrap(), expected); + } + + #[test] + fn title_names_bound_the_bytes_read_from_siblings() { + let root = folder("budget"); + let game = root.join("Game.exe"); + executable(&game, &["GameLauncherPipe"]); + executable(&root.join("First.exe"), &["FirstLauncherPipe"]); + executable(&root.join("Second.exe"), &["SecondLauncherPipe"]); + let size = fs::metadata(root.join("First.exe")).unwrap().len(); + let names = discover(&game, size + 8); + fs::remove_dir_all(&root).unwrap(); + assert_eq!(names.unwrap(), ["FirstLauncherPipe", "GameLauncherPipe"]); + } + + #[test] + fn title_names_merge_case_insensitively_and_cap_sibling_names() { + let root = folder("merge"); + let game = root.join("Game.exe"); + executable( + &game, + &[ + "ALauncherPipe", + "BLauncherPipe", + "CLauncherPipe", + "GTAVLauncher_Pipe", + ], + ); + executable( + &root.join("A.exe"), + &["gtavLauncher_Pipe", "ELauncherPipe", "FLauncherPipe"], + ); + executable( + &root.join("B.exe"), + &["GLauncherPipe", "HLauncherPipe", "ILauncherPipe"], + ); + let names = title_pipe_names(&game); + fs::remove_dir_all(&root).unwrap(); + assert_eq!( + names.unwrap(), + [ + "ALauncherPipe", + "BLauncherPipe", + "CLauncherPipe", + "ELauncherPipe", + "FLauncherPipe", + "GLauncherPipe", + "GTAVLauncher_Pipe", + "HLauncherPipe" + ] + ); + } + #[test] fn identity_replies_echo_only_a_valid_challenge() { struct Split(R); diff --git a/tools/rockstar-launcher/src/main.rs b/tools/rockstar-launcher/src/main.rs index 0913c6d548..cc2d294218 100644 --- a/tools/rockstar-launcher/src/main.rs +++ b/tools/rockstar-launcher/src/main.rs @@ -146,14 +146,21 @@ fn run() -> Result> { None }; let mut identity_listeners = Vec::new(); + let mut identity_names = Vec::new(); if session.is_some() { - for name in - droiddeck_rockstar_launcher::identity::pipe_names(&mut std::fs::File::open(&exe)?)? - { - identity_listeners.push(Listener::new(&name, Duration::from_secs(90))?); + identity_names = droiddeck_rockstar_launcher::identity::title_pipe_names(&exe)?; + for name in &identity_names { + identity_listeners.push(Listener::new(name, Duration::from_secs(90))?); } } - log("launcher pipes created"); + log(&format!( + "launcher pipes created, identity: {}", + if identity_names.is_empty() { + "none".to_owned() + } else { + identity_names.join(", ") + } + )); let mut command = std::process::Command::new(exe); command.current_dir(workdir).args(args?); if session.is_some() { @@ -256,7 +263,9 @@ fn run() -> Result> { } let _ = result.send(outcome); }); - Ok(wait_for_game(&mut child, handshake)?.code().unwrap_or(1)) + let code = wait_for_game(&mut child, handshake)?.code().unwrap_or(1); + log(&format!("game exited with code {code}")); + Ok(code) } fn main() { diff --git a/tools/tests/test_client_zram_focus.py b/tools/tests/test_client_zram_focus.py index db2d3f80e1..bcc5e4768b 100644 --- a/tools/tests/test_client_zram_focus.py +++ b/tools/tests/test_client_zram_focus.py @@ -80,7 +80,7 @@ class ClientZramFocusTest(unittest.TestCase): def test_refocus_restarts_the_delay_and_game_exit_restores_a_packed_client(self): source = SCRIPT.read_text() - start = source.index(' if [ "$_bl_game" = 1 ] && bl_game_focused; then') + start = source.index(' _bl_focus=1\n') stop = source.index(' bl_watch_nap\n', start) body = source[start:stop] harness = ''' @@ -125,7 +125,7 @@ bl_client_pressure_finish() { :; } bl_session_pressure() { :; } bl_client_can_pageout() { return 0; } bl_client_can_readback() { [ "${readback:-1}" = 1 ]; } -bl_game_focused() { [ "$focused" = 1 ]; } +bl_game_focused() { [ "$focused" = 1 ] && return 0; [ "$focused" = 2 ] && return 2; return 1; } bl_cap_due() { [ "$cap_due" = 1 ]; } bl_over_cap() { [ "$over_cap" = 1 ]; } bl_zram_send() { echo "send:$1:$3"; } @@ -199,6 +199,97 @@ echo "restored:$_bl_unpack" self.assertEqual('', result.stderr) self.assertEqual(['send:1:client', 'deferred:1', 'send:0:client', 'restored:0'], result.stdout.splitlines()) + def test_client_in_front_of_a_running_game_is_read_back_and_compressed_again_later(self): + result = run_bash(self.monitor_harness() + ''' +tick 0 1 1 0 0 +tick 20 1 1 0 0 +tick 25 1 0 0 0 +echo "away:$_bl_packed" +tick 30 1 0 0 0 +echo "read:$_bl_packed:$_bl_unpack" +tick 35 1 0 0 0 +tick 40 1 1 0 0 +tick 55 1 1 0 0 +tick 60 1 1 0 0 +echo "again:$_bl_packed" +tick 65 0 0 0 0 +''') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + self.assertEqual(['send:1:client', 'away:20', 'send:0:client', 'read:-1:0', 'send:1:client', 'again:60', 'send:0:client'], + result.stdout.splitlines()) + + def test_unknown_focus_keeps_the_client_compressed(self): + result = run_bash(self.monitor_harness() + ''' +tick 0 1 1 0 0 +tick 20 1 1 0 0 +tick 25 1 2 0 0 +tick 40 1 2 0 0 +echo "unknown:$_bl_packed:$_bl_unpack" +tick 45 1 0 0 0 +tick 48 1 2 0 0 +tick 52 1 0 0 0 +tick 56 1 0 0 0 +echo "flicker:$_bl_packed" +tick 57 1 0 0 0 +echo "read:$_bl_packed" +tick 60 0 2 0 0 +''') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + self.assertEqual(['send:1:client', 'unknown:20:1', 'flicker:20', 'send:0:client', 'read:-1'], + result.stdout.splitlines()) + + def test_a_short_look_at_the_client_keeps_it_compressed(self): + result = run_bash(self.monitor_harness() + ''' +tick 0 1 1 0 0 +tick 20 1 1 0 0 +tick 25 1 0 0 0 +tick 28 1 1 0 0 +tick 30 1 0 0 0 +tick 34 1 0 0 0 +echo "packed:$_bl_packed" +''') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + self.assertEqual(['send:1:client', 'packed:20'], result.stdout.splitlines()) + + def test_client_in_front_waits_for_memory_and_a_ram_cap_keeps_it_compressed(self): + result = run_bash(self.monitor_harness() + ''' +tick 0 1 1 0 0 +tick 20 1 1 0 0 +readback=0 +tick 25 1 0 0 0 +tick 35 1 0 0 0 +echo "tight:$_bl_packed" +readback=1 +tick 40 1 0 0 0 +echo "eased:$_bl_packed" +_bl_ram_cap=1048576 +tick 60 1 1 0 0 +tick 80 1 1 0 0 +tick 85 1 0 0 0 +tick 100 1 0 0 0 +echo "capped:$_bl_packed" +tick 105 0 0 0 0 +''') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + self.assertEqual(['send:1:client', 'tight:20', 'send:0:client', 'eased:-1', 'send:1:client', 'capped:80', 'send:0:client'], + result.stdout.splitlines()) + + def test_client_in_front_without_compression_reads_nothing_back(self): + result = run_bash(self.monitor_harness() + ''' +BL_ZRAM_CLIENT=0 +tick 0 1 1 0 0 +tick 25 1 0 0 0 +tick 40 1 0 0 0 +tick 45 0 0 0 0 +''') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + self.assertEqual('', result.stdout) + def test_scan_keeps_the_running_game_and_ignores_steams_own_reaper(self): temp = tempfile.TemporaryDirectory() self.addCleanup(temp.cleanup) @@ -219,7 +310,8 @@ echo "restored:$_bl_unpack" %s check() { BL_DESKTOP=$1 BL_LAUNCH_DIR=$2 _bl_apps=$3 - if bl_game_focused; then echo yes; else echo no; fi + bl_game_focused + echo $? } check "" "$dir" " 413150" check "" "$dir" " 1245620" @@ -227,7 +319,10 @@ printf '%%s\\n' '{"focusedApp": 999}' > "$dir/agent/focus.json" check "" "$dir" " 413150" printf '%%s\\n' '{"focusedApp": 769}' > "$dir/agent/focus.json" check "" "$dir" " 413150" +printf '%%s\\n' '{"t": 2}' > "$dir/agent/focus.json" +check "" "$dir" " 413150" rm -f "$dir/agent/focus.json" +check "" "$dir" " 413150" check 1 "$dir" " 413150" check "" "" " 413150" ''' % focus @@ -238,7 +333,7 @@ check "" "" " 413150" (launch / 'agent' / 'focus.json').write_text('{"t": 1, "focusedApp": 413150}\n') result = run_bash('dir=%s\n%s' % (launch, script)) self.assertEqual(0, result.returncode, result.stderr) - self.assertEqual(['yes', 'no', 'no', 'no', 'yes', 'yes'], result.stdout.splitlines()) + self.assertEqual(['0', '1', '1', '1', '2', '2', '0', '0'], result.stdout.splitlines()) @staticmethod def write_cmd(root, pid, args): diff --git a/tools/tests/test_desktop_bookmarks.py b/tools/tests/test_desktop_bookmarks.py index 4c53dc6894..802e10fe44 100644 --- a/tools/tests/test_desktop_bookmarks.py +++ b/tools/tests/test_desktop_bookmarks.py @@ -162,6 +162,80 @@ class DolphinPlacesTest(unittest.TestCase): self.assertEqual(1, len(root.findall("bookmark"))) self.assertEqual("My games", root.findtext("bookmark/title")) + def volumes(self, entries): + listing = self.home / "volumes.json" + listing.write_text(json.dumps(entries)) + os.environ["BL_DESKTOP_VOLUMES"] = str(listing) + return MODULE["removable_volumes"]() + + def update_volumes(self, volumes): + MODULE["update_places"](self.places, volumes, "DroidDeckRemovableVolume", "drive-removable-media", "droiddeck-volume-") + return ET.parse(self.places).getroot() + + def test_all_readable_volumes_without_steam_libraries(self): + card = self.home / "ABCD-1234" + usb = self.home / "USB café & " + card.mkdir() + usb.mkdir() + missing = self.home / "unplugged" + entries = [{"path": str(card), "label": "Card"}, {"path": str(usb), "label": "USB & "}, + {"path": str(missing), "label": "Gone"}, {"path": "relative", "label": "Invalid"}] + volumes = self.volumes(entries) + self.assertEqual({card.as_uri(): "Card", usb.as_uri(): "USB & "}, volumes) + root = self.update_volumes(volumes) + self.assertEqual(2, len(root.findall("bookmark"))) + self.assertEqual("USB & ", root.findall("bookmark")[1].findtext("title")) + self.assertFalse((card / "steamapps").exists()) + self.assertEqual("drive-removable-media", root.find("bookmark/info/metadata/{" + MODULE["ICON_NS"] + "}icon").get("name")) + + def test_main_adds_volumes_without_changing_gtk_or_steam_selection(self): + card = self.home / "card" + card.mkdir() + self.volumes([{"path": str(card), "label": "Card"}]) + with patch.object(Path, "home", return_value=self.home), patch.dict(os.environ, {"XDG_DATA_HOME": str(self.data)}): + MODULE["main"]() + root = ET.parse(self.places).getroot() + self.assertEqual({self.steam.as_uri(), card.as_uri()}, {b.get("href") for b in root.findall("bookmark")}) + self.assertFalse((self.home / ".config/gtk-3.0/bookmarks").exists()) + self.volumes([]) + MODULE["main"]() + root = ET.parse(self.places).getroot() + self.assertEqual([self.steam.as_uri()], [b.get("href") for b in root.findall("bookmark")]) + + def test_unreadable_volume_is_not_offered(self): + card = self.home / "card" + card.mkdir() + with patch("os.scandir", side_effect=PermissionError): + self.assertEqual({}, self.volumes([{"path": str(card), "label": "Card"}])) + + def test_volume_refresh_preserves_steam_personal_and_hidden_places(self): + card = self.home / "card" + card.mkdir() + self.update({self.steam.as_uri(): "Steam"}) + root = self.update_volumes({card.as_uri(): "Card"}) + volume = root.findall("bookmark")[1] + metadata = volume.find("info/metadata[@owner='http://www.kde.org']") + ET.SubElement(metadata, "IsHidden").text = "true" + ET.SubElement(root, "bookmark", {"href": "file:///root/Documents"}) + self.places.write_bytes(ET.tostring(root)) + root = self.update_volumes({card.as_uri(): "Renamed"}) + self.assertEqual("true", root.findall("bookmark")[1].findtext("info/metadata/IsHidden")) + before = self.places.read_bytes() + self.update_volumes({card.as_uri(): "Renamed"}) + self.assertEqual(before, self.places.read_bytes()) + self.update({self.steam.as_uri(): "Steam"}) + root = self.update_volumes({}) + self.assertEqual([self.steam.as_uri(), "file:///root/Documents"], [b.get("href") for b in root.findall("bookmark")]) + + def test_personal_volume_place_is_not_duplicated_or_removed(self): + card = self.home / "card" + card.mkdir() + self.places.write_text(f'My card') + before = self.places.read_bytes() + self.update_volumes({card.as_uri(): "Card"}) + self.update_volumes({}) + self.assertEqual(before, self.places.read_bytes()) + def test_invalid_xml_is_not_overwritten(self): self.places.write_text("unfinished") with self.assertRaises(ET.ParseError): diff --git a/tools/tests/test_droiddeck_agent.py b/tools/tests/test_droiddeck_agent.py index a1adca90c6..d6d640d887 100644 --- a/tools/tests/test_droiddeck_agent.py +++ b/tools/tests/test_droiddeck_agent.py @@ -867,6 +867,82 @@ const value = subscribe => { return e +class FocusSnapshotTest(unittest.TestCase): + def test_publication_failure_retries_unknown_and_recovers(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'focus.json' + watcher = agent.FocusWatcher(path) + watcher.publish({'focusedApp': 42}) + write_json = agent.write_json + writes = [] + + def write(path, value): + writes.append(value) + if len(writes) == 1: + raise OSError('unavailable') + write_json(path, value) + + with patch.object(threading.Thread, 'start'), \ + patch.object(watcher.changed, 'wait', side_effect=[True, True, True, StopIteration]), \ + patch.object(agent, 'vr_scene_app', return_value=None), \ + patch.object(agent, 'focus_snapshot', side_effect=[OSError('unavailable'), OSError('unavailable'), {'focusedApp': 42}]), \ + patch.object(agent, 'write_json', side_effect=write), \ + patch.object(agent.time, 'sleep'), \ + patch.object(agent, 'log'): + with self.assertRaises(StopIteration): + watcher.run() + self.assertEqual(writes, [{'seq': 2}, {'seq': 2}, {'focusedApp': 42, 'seq': 3}]) + self.assertEqual(json.loads(path.read_text()), {'focusedApp': 42, 'seq': 3}) + + def test_successful_snapshot_write_failure_retries(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'focus.json' + watcher = agent.FocusWatcher(path) + with patch.object(agent, 'write_json', side_effect=OSError('unavailable')), patch.object(agent, 'log'): + watcher.publish({'focusedApp': 42}) + self.assertIsNone(watcher.last) + self.assertEqual(watcher.seq, 0) + self.assertTrue(watcher.changed.is_set()) + watcher.publish({'focusedApp': 42}) + self.assertEqual(json.loads(path.read_text()), {'focusedApp': 42, 'seq': 1}) + + def test_collection_failure_invalidates_and_recovery_republishes(self): + for error in (OSError('unavailable'), agent.AgentError('X', 'unavailable')): + with self.subTest(error=type(error).__name__), tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'focus.json' + watcher = agent.FocusWatcher(path) + snapshot = {'focusedApp': 42, 't': 1} + watcher.publish(snapshot) + observed = [] + + def collect(): + observed.append(json.loads(path.read_text())) + if len(observed) == 1: + raise error + return dict(snapshot, t=2) + + with patch.object(threading.Thread, 'start'), \ + patch.object(watcher.changed, 'wait', side_effect=[True, True, StopIteration]), \ + patch.object(agent, 'vr_scene_app', return_value=None), \ + patch.object(agent, 'focus_snapshot', side_effect=collect), \ + patch.object(agent.time, 'sleep'), \ + patch.object(agent, 'log'): + with self.assertRaises(StopIteration): + watcher.run() + self.assertEqual(observed, [dict(snapshot, seq=1), {'seq': 2}]) + self.assertEqual(json.loads(path.read_text()), {'focusedApp': 42, 't': 2, 'seq': 3}) + + def test_unchanged_successful_focus_stays_valid(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'focus.json' + watcher = agent.FocusWatcher(path) + watcher.publish({'focusedApp': 769, 't': 1}) + with patch.object(agent, 'write_json') as write: + watcher.publish({'focusedApp': 769, 't': 100}) + write.assert_not_called() + self.assertEqual(json.loads(path.read_text()), {'focusedApp': 769, 't': 1, 'seq': 1}) + + class VrFocusTest(unittest.TestCase): def test_scene_dashboard_and_external_focus_changes(self): focus = agent.VrSceneFocus() diff --git a/tools/tests/test_droiddeck_fex.py b/tools/tests/test_droiddeck_fex.py index 35c8201d58..10cce2770d 100644 --- a/tools/tests/test_droiddeck_fex.py +++ b/tools/tests/test_droiddeck_fex.py @@ -8,6 +8,7 @@ import shutil import stat import struct import subprocess +import sys import tempfile import unittest from pathlib import Path @@ -451,6 +452,331 @@ class PrepareTest(FexTestCase): self.assertIn("built the x86 runtime", self.quiet(FEX["prepare"])[1]) self.assertEqual(sorted(os.listdir(root.parent)), ["config", "lock", "rootfs", "status.json"]) + def test_wayland_and_its_ffi_dependency_come_from_the_newer_runtime(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + names = ("libwayland-client.so.0", "libwayland-cursor.so.0", "libwayland-egl.so.1", + "libwayland-server.so.0", "libffi.so.8") + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + for name in names: + base = sniper / "files/lib" / arch / name + if name != "libffi.so.8": + self.write(base, b"old ABI") + source = provider / "files/lib" / arch / name + self.write(str(source) + ".new", b"new ABI " + name.encode()) + os.symlink(name + ".new", source) + self.write(sniper / "files/lib" / arch / "libffi.so.7", b"old ffi") + fex, _ = self.quiet(FEX["prepare"]) + root = Path(fex["rootfs"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + for name in names: + library = root / "lib" / arch / name + expected = sniper if name == "libwayland-cursor.so.0" else provider + self.assertEqual(library.read_bytes(), b"old ABI" if expected == sniper else b"new ABI " + name.encode()) + self.assertEqual((root / "lib" / arch / "libffi.so.7").read_bytes(), b"old ffi") + self.assertEqual((sniper / "files/lib/x86_64-linux-gnu/libwayland-client.so.0").read_bytes(), b"old ABI") + + @unittest.skipUnless(shutil.which("cc"), "C compiler unavailable") + def test_bundled_library_resolves_the_new_wayland_symbol(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + base = sniper / "files/lib/x86_64-linux-gnu" + newer = provider / "files/lib/x86_64-linux-gnu" + source = self.tmp / "library.c" + self.write(newer / "libffi.so.8", b"ffi") + for folder, symbol in ((base, "wl_proxy_marshal"), (newer, "wl_proxy_marshal_flags")): + source.write_text("void *%s(void) { return 0; }\n" % symbol) + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-Wl,-soname,libwayland-client.so.0", + "-o", str(folder / "libwayland-client.so.0"), str(source)], check=True, capture_output=True) + fex, _ = self.quiet(FEX["prepare"]) + root = Path(fex["rootfs"]) / "lib/x86_64-linux-gnu" + source.write_text("extern void *wl_proxy_marshal_flags(void);\nvoid *probe(void) { return wl_proxy_marshal_flags(); }\n") + probe = self.tmp / "libprobe.so" + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-o", str(probe), str(source), + "-L" + str(newer), "-l:libwayland-client.so.0", "-Wl,-rpath," + str(root)], + check=True, capture_output=True) + command = [sys.executable, "-c", + "import ctypes,sys; " + "ctypes.CDLL(sys.argv[2], mode=ctypes.RTLD_GLOBAL) if len(sys.argv) > 2 else None; " + "ctypes.CDLL(sys.argv[1]).probe()", + str(probe)] + env = {k: v for k, v in os.environ.items() if not k.startswith("LD_")} + broken = subprocess.run(command + [str(base / "libwayland-client.so.0")], env=env, capture_output=True, text=True) + self.assertNotEqual(broken.returncode, 0) + self.assertIn("undefined symbol: wl_proxy_marshal_flags", broken.stderr) + fixed = subprocess.run(command, env=env, capture_output=True, text=True) + self.assertEqual(fixed.returncode, 0, fixed.stderr) + + def test_gbm_and_its_dependencies_use_the_newer_runtime_on_both_architectures(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + names = ("libgbm.so.1", "libdrm.so.2", "libexpat.so.1") + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + for name in names: + self.write(sniper / "files/lib" / arch / name, b"old ABI") + self.write(provider / "files/lib" / arch / name, b"new ABI " + name.encode()) + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + for name in names: + self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).read_bytes(), b"new ABI " + name.encode()) + + def test_gbm_requires_usable_provider_dependencies_on_both_architectures(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + for name in ("libgbm.so.1", "libdrm.so.2"): + self.write(sniper / "files/lib" / arch / name, b"base") + self.write(provider / "files/lib" / arch / name, b"provider") + os.symlink("missing-expat.so", provider / "files/lib" / arch / "libexpat.so.1") + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + root = Path(fex["rootfs"]) / "lib" / arch + self.assertEqual((root / "libgbm.so.1").read_bytes(), b"base") + self.assertEqual((root / "libdrm.so.2").read_bytes(), b"provider") + + @unittest.skipUnless(shutil.which("cc"), "C compiler unavailable") + def test_bundled_library_resolves_the_new_gbm_symbol(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + base = sniper / "files/lib/x86_64-linux-gnu" + newer = provider / "files/lib/x86_64-linux-gnu" + source = self.tmp / "gbm.c" + self.write(newer / "libdrm.so.2", b"drm") + self.write(newer / "libexpat.so.1", b"expat") + for folder, symbol in ((base, "gbm_bo_create_with_modifiers"), (newer, "gbm_bo_create_with_modifiers2")): + source.write_text("void *%s(void) { return 0; }\n" % symbol) + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-Wl,-soname,libgbm.so.1", + "-o", str(folder / "libgbm.so.1"), str(source)], check=True, capture_output=True) + fex, _ = self.quiet(FEX["prepare"]) + root = Path(fex["rootfs"]) / "lib/x86_64-linux-gnu" + source.write_text("extern void *gbm_bo_create_with_modifiers2(void);\n" + "void *probe(void) { return gbm_bo_create_with_modifiers2(); }\n") + probe = self.tmp / "libgbmprobe.so" + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-o", str(probe), str(source), + "-L" + str(newer), "-l:libgbm.so.1", "-Wl,-rpath," + str(root)], + check=True, capture_output=True) + command = [sys.executable, "-c", + "import ctypes,sys; " + "ctypes.CDLL(sys.argv[2], mode=ctypes.RTLD_GLOBAL) if len(sys.argv) > 2 else None; " + "ctypes.CDLL(sys.argv[1]).probe()", + str(probe)] + env = {k: v for k, v in os.environ.items() if not k.startswith("LD_")} + broken = subprocess.run(command + [str(base / "libgbm.so.1")], env=env, capture_output=True, text=True) + self.assertNotEqual(broken.returncode, 0) + self.assertIn("undefined symbol: gbm_bo_create_with_modifiers2", broken.stderr) + fixed = subprocess.run(command, env=env, capture_output=True, text=True) + self.assertEqual(fixed.returncode, 0, fixed.stderr) + + def test_freetype_and_dependencies_use_the_newer_runtime_on_both_architectures(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + names = ("libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1", + "libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1") + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + for name in names: + self.write(sniper / "files/lib" / arch / name, b"base") + self.write(provider / "files/lib" / arch / name, b"new") + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + for name in names: + self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).read_bytes(), b"new") + self.assertEqual((sniper / "files/lib" / arch / name).read_bytes(), b"base") + + @unittest.skipUnless(shutil.which("cc"), "C compiler unavailable") + def test_bundled_library_resolves_the_new_freetype_symbol(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + base = sniper / "files/lib/x86_64-linux-gnu" + newer = provider / "files/lib/x86_64-linux-gnu" + source = self.tmp / "freetype.c" + for folder, symbol in ((base, "FT_Init_FreeType"), (newer, "FT_Get_Color_Glyph_Paint")): + source.write_text("void *%s(void) { return 0; }\n" % symbol) + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-Wl,-soname,libfreetype.so.6", + "-o", str(folder / "libfreetype.so.6"), str(source)], check=True, capture_output=True) + fex, _ = self.quiet(FEX["prepare"]) + root = Path(fex["rootfs"]) / "lib/x86_64-linux-gnu" + source.write_text("extern void *FT_Get_Color_Glyph_Paint(void);\nvoid *probe(void) { return FT_Get_Color_Glyph_Paint(); }\n") + probe = self.tmp / "libprobe.so" + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-o", str(probe), str(source), + "-L" + str(newer), "-l:libfreetype.so.6", "-Wl,-rpath," + str(root)], + check=True, capture_output=True) + command = [sys.executable, "-c", + "import ctypes,sys; " + "ctypes.CDLL(sys.argv[2], mode=ctypes.RTLD_GLOBAL) if len(sys.argv) > 2 else None; " + "ctypes.CDLL(sys.argv[1]).probe()", str(probe)] + env = {k: v for k, v in os.environ.items() if not k.startswith("LD_")} + broken = subprocess.run(command + [str(base / "libfreetype.so.6")], env=env, capture_output=True, text=True) + self.assertNotEqual(broken.returncode, 0) + self.assertIn("undefined symbol: FT_Get_Color_Glyph_Paint", broken.stderr) + fixed = subprocess.run(command, env=env, capture_output=True, text=True) + self.assertEqual(fixed.returncode, 0, fixed.stderr) + + def test_missing_freetype_provider_keeps_base_on_both_architectures(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + self.graphics(sniper) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + self.write(sniper / "files/lib" / arch / "libfreetype.so.6", b"base") + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / "libfreetype.so.6").read_bytes(), b"base") + + def test_missing_provider_libraries_keep_the_base_runtime_libraries(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + self.graphics(sniper) + base = self.write(sniper / "files/lib/x86_64-linux-gnu/libwayland-client.so.0", b"base wayland") + fex, _ = self.quiet(FEX["prepare"]) + self.assertEqual((Path(fex["rootfs"]) / "lib/x86_64-linux-gnu/libwayland-client.so.0").read_bytes(), b"base wayland") + + def test_provider_symlinks_require_existing_targets_on_both_architectures(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + base = sniper / "files/lib" / arch + newer = provider / "files/lib" / arch + self.write(base / "libwayland-client.so.0", b"base") + os.symlink("missing-client.so", newer / "libwayland-client.so.0") + os.symlink("missing-ffi.so", newer / "libffi.so.8") + self.write(newer / "wayland-server-real.so", b"provider") + os.symlink("wayland-server-real.so", newer / "libwayland-server.so.0") + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + root = Path(fex["rootfs"]) / "lib" / arch + self.assertEqual((root / "libwayland-client.so.0").read_bytes(), b"base") + self.assertFalse(os.path.lexists(root / "libffi.so.8")) + self.assertFalse(os.path.lexists(root / "libwayland-server.so.0")) + + def test_wayland_requires_usable_provider_ffi_on_both_architectures(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + for ffi_state in ("missing", "dangling"): + with self.subTest(ffi_state=ffi_state): + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + base = sniper / "files/lib" / arch + newer = provider / "files/lib" / arch + for name in ("libwayland-client.so.0", "libwayland-server.so.0", "libwayland-cursor.so.0"): + self.write(base / name, b"base") + self.write(newer / name, b"provider") + if ffi_state == "dangling": + os.symlink("missing-ffi.so", newer / "libffi.so.8") + marker = self.home / ".local/share/droiddeck-fex/rootfs/.droiddeck-fex" + if marker.exists(): + marker.unlink() + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + root = Path(fex["rootfs"]) / "lib" / arch + for name in ("libwayland-client.so.0", "libwayland-server.so.0", "libwayland-cursor.so.0"): + self.assertEqual((root / name).read_bytes(), b"base") + self.assertFalse(os.path.lexists(root / "libffi.so.8")) + + def test_wayland_cursor_requires_usable_provider_client_on_both_architectures(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + for client_state in ("missing", "dangling"): + with self.subTest(client_state=client_state): + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + base = sniper / "files/lib" / arch + newer = provider / "files/lib" / arch + self.write(base / "libwayland-client.so.0", b"base client") + self.write(base / "libwayland-cursor.so.0", b"base cursor") + self.write(newer / "libwayland-cursor.so.0", b"provider cursor") + self.write(newer / "libffi.so.8", b"provider ffi") + if client_state == "dangling": + os.symlink("missing-client.so", newer / "libwayland-client.so.0") + marker = self.home / ".local/share/droiddeck-fex/rootfs/.droiddeck-fex" + if marker.exists(): + marker.unlink() + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + root = Path(fex["rootfs"]) / "lib" / arch + self.assertEqual((root / "libwayland-client.so.0").read_bytes(), b"base client") + self.assertEqual((root / "libwayland-cursor.so.0").read_bytes(), b"base cursor") + self.assertEqual((root / "libffi.so.8").read_bytes(), b"provider ffi") + + def test_restored_provider_clients_rebuild_the_rootfs_without_marker_changes(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + self.write(sniper / "files/lib" / arch / "libwayland-client.so.0", b"base") + self.write(provider / "files/lib" / arch / "libffi.so.8", b"ffi") + os.symlink("client-real.so", provider / "files/lib" / arch / "libwayland-client.so.0") + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / "libwayland-client.so.0").read_bytes(), b"base") + self.write(provider / "files/lib" / arch / "client-real.so", b"restored") + fex, said = self.quiet(FEX["prepare"]) + self.assertIn("built the x86 runtime", said) + self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / "libwayland-client.so.0").read_bytes(), b"restored") + self.assertNotIn("built the x86 runtime", self.quiet(FEX["prepare"])[1]) + client = provider / "files/lib/i386-linux-gnu/client-real.so" + client.write_bytes(b"updated client") + fex, said = self.quiet(FEX["prepare"]) + self.assertIn("built the x86 runtime", said) + self.assertEqual((Path(fex["rootfs"]) / "lib/i386-linux-gnu/libwayland-client.so.0").read_bytes(), b"updated client") + + @unittest.skipUnless(shutil.which("cc"), "C compiler unavailable") + def test_base_cursor_works_with_guest_selected_old_client(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + base = sniper / "files/lib/x86_64-linux-gnu" + newer = provider / "files/lib/x86_64-linux-gnu" + source = self.tmp / "cursor.c" + self.write(newer / "libffi.so.8", b"ffi") + for folder, symbol in ((base, "wl_proxy_marshal"), (newer, "wl_proxy_marshal_flags")): + source.write_text("void %s(void) {}\n" % symbol) + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-Wl,-soname,libwayland-client.so.0", + "-o", str(folder / "libwayland-client.so.0"), str(source)], check=True, capture_output=True) + source.write_text("extern void %s(void); void probe(void) { %s(); }\n" % (symbol, symbol)) + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-o", str(folder / "libwayland-cursor.so.0"), + str(source), "-L" + str(folder), "-l:libwayland-client.so.0"], check=True, capture_output=True) + fex, _ = self.quiet(FEX["prepare"]) + cursor = Path(fex["rootfs"]) / "lib/x86_64-linux-gnu/libwayland-cursor.so.0" + command = [sys.executable, "-c", "import ctypes,sys; ctypes.CDLL(sys.argv[1], mode=ctypes.RTLD_GLOBAL); ctypes.CDLL(sys.argv[2]).probe()", str(base / "libwayland-client.so.0")] + env = {k: v for k, v in os.environ.items() if not k.startswith("LD_")} + broken = subprocess.run(command + [str(newer / "libwayland-cursor.so.0")], env=env, capture_output=True, text=True) + self.assertNotEqual(broken.returncode, 0) + self.assertIn("undefined symbol: wl_proxy_marshal_flags", broken.stderr) + fixed = subprocess.run(command + [str(cursor)], env=env, capture_output=True, text=True) + self.assertEqual(fixed.returncode, 0, fixed.stderr) + + def test_the_old_rootfs_layout_is_rebuilt(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + self.graphics(sniper) + with mock.patch.dict(G, {"ROOTFS_LAYOUT": 6}): + self.quiet(FEX["prepare"]) + _, said = self.quiet(FEX["prepare"]) + self.assertIn("built the x86 runtime", said) + self.assertNotIn("built the x86 runtime", self.quiet(FEX["prepare"])[1]) + def test_the_built_x86_runtime_holds_nothing_that_leaves_it(self): self.fex_tool() sniper = self.runtime() diff --git a/tools/tests/test_fex_gl_thunk_errors.py b/tools/tests/test_fex_gl_thunk_errors.py new file mode 100644 index 0000000000..3afa881e47 --- /dev/null +++ b/tools/tests/test_fex_gl_thunk_errors.py @@ -0,0 +1,474 @@ +import os +import re +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest +from unittest import mock + +PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0005-gl-thunk-forward-x-errors.patch" + + +def added(path, start, end): + text = PATCH.read_text() + section = re.search(r"^diff --git a/%s .*?(?=^diff --git |\Z)" % re.escape(path), text, re.S | re.M) + lines = [line[1:] for line in section.group(0).splitlines() if line.startswith("+") and not line.startswith("+++")] + body = "\n".join(lines) + first = body.index(start) + last = body.index(end, first) + len(end) + return body[first:last] + + +HARNESS = r""" +#include +#include +#include +#include +#include +#include +#include +#include +using guest_long = long; + +static std::mutex host_user_lock; +static std::mutex guest_user_lock; +static void guest_lock(Display*) { guest_user_lock.lock(); } +static void guest_unlock(Display*) { guest_user_lock.unlock(); } +static _XLockPtrs guest_lock_fns {guest_lock, guest_unlock}; + +struct X11Manager { + MUTEX_SOURCE + std::map<_XDisplay*, _XDisplay*> displays; + FORWARD_SOURCE + FIND_SOURCE + static XErrorHandler HostXSetErrorHandler(XErrorHandler Handler) { return XSetErrorHandler(Handler); } + static void HostXLockDisplay(Display*) { host_user_lock.lock(); } + static void HostXUnlockDisplay(Display*) { host_user_lock.unlock(); } +}; + +static X11Manager x11_manager; +static int (*pending_forward)(void*, guest_long, int, int, int); + +template +static void MakeHostTrampolineForGuestFunctionAt(uintptr_t, uintptr_t, F** Func) { *Func = pending_forward; } + +static int guest_set_calls; +#define XSetErrorHandler(h) (guest_set_calls++, ::XSetErrorHandler(h)) +GUEST_SOURCE +#undef XSetErrorHandler + +HOST_SOURCE + +static Display* app_display; +static XErrorEvent app_event; +static int app_calls; +static int app_handler(Display* display, XErrorEvent* event) { + app_display = display; + app_event = *event; + app_calls++; + return 7; +} + +static int previous_calls; +static Display* previous_display; +static int previous_handler(Display* display, XErrorEvent*) { + previous_calls++; + previous_display = display; + return 3; +} + +static int guest_forward(void* display, guest_long resourceid, int error_code, int request_code, int minor_code) { + return ForwardXError(static_cast(display), resourceid, error_code, request_code, minor_code); +} + +static _XDisplay guest_connection; + +static int raise_on_host(XErrorHandler handler, Display* display, XErrorEvent* event) { + std::lock_guard held(host_user_lock); + return handler(display, event); +} + +int main(int argc, char** argv) { + auto host = reinterpret_cast(uintptr_t {0x1000}); + auto guest = &guest_connection; + auto other = reinterpret_cast(uintptr_t {0x3000}); + guest_connection.request = 44; + guest_connection.last_request_read = 44; + guest_connection.lock_fns = &guest_lock_fns; + x11_manager.displays[guest] = host; + pending_forward = guest_forward; + XSetErrorHandler(previous_handler); + fexfn_impl_libGL_GL_SetGuestXErrorForward(0, 0); + fexfn_impl_libGL_GL_SetGuestXErrorForward(0, 0); + XErrorHandler installed = XSetErrorHandler(nullptr); + XSetErrorHandler(installed); + + XErrorEvent event {}; + event.type = 0; + event.display = host; + event.resourceid = 0xffffffff; + event.serial = 9000; + event.error_code = 163; + event.request_code = 148; + event.minor_code = 0; + + XSetErrorHandler(app_handler); + if (argc > 1 && strcmp(argv[1], "reentry") == 0) { + std::unique_lock lock(x11_manager.mutex); + int reentry = raise_on_host(installed, host, &event); + printf("reentry=%d app_calls=%d\n", reentry, app_calls); + return 0; + } + if (argc > 1 && strcmp(argv[1], "crosslock") == 0) { + host_user_lock.lock(); + std::mutex ready_lock; + std::unique_lock ready(ready_lock); + std::condition_variable guest_held; + bool held = false; + std::thread other_thread([&] { + guest_user_lock.lock(); + { + std::lock_guard notify(ready_lock); + held = true; + } + guest_held.notify_one(); + host_user_lock.lock(); + host_user_lock.unlock(); + guest_user_lock.unlock(); + }); + guest_held.wait(ready, [&] { return held; }); + ready.unlock(); + int crossed = installed(host, &event); + host_user_lock.unlock(); + other_thread.join(); + printf("crosslock=%d app_calls=%d\n", crossed, app_calls); + return 0; + } + int owned = raise_on_host(installed, host, &event); + XErrorHandler after = XSetErrorHandler(installed); + int foreign = raise_on_host(installed, other, &event); + + printf("owned=%d app_calls=%d app_display_is_guest=%d serial=%lu error=%d request=%d minor=%d resource=%lx handler_kept=%d guest_set_calls=%d\n", + owned, app_calls, app_display == guest, app_event.serial, app_event.error_code, app_event.request_code, + app_event.minor_code, app_event.resourceid, after == app_handler, guest_set_calls); + printf("foreign=%d previous_calls=%d previous_display_is_other=%d\n", foreign, previous_calls, previous_display == other); + return 0; +} +""" + + +REAL_HARNESS = r""" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using guest_long = long; + +struct X11Manager { + MUTEX_SOURCE + std::map<_XDisplay*, _XDisplay*> displays; + FORWARD_SOURCE + FIND_SOURCE + static XErrorHandler HostXSetErrorHandler(XErrorHandler Handler) { return XSetErrorHandler(Handler); } + static void HostXLockDisplay(Display* a) { XLockDisplay(a); } + static void HostXUnlockDisplay(Display* a) { XUnlockDisplay(a); } +}; + +static X11Manager x11_manager; +static int (*pending_forward)(void*, guest_long, int, int, int); + +template +static void MakeHostTrampolineForGuestFunctionAt(uintptr_t, uintptr_t, F** Func) { *Func = pending_forward; } + +GUEST_SOURCE + +HOST_SOURCE + +static Display* host; +static Display* guest; +static std::atomic app_calls; +static std::atomic guest_calls; +static unsigned long app_serial; +static int app_error; +static int app_minor; +static std::atomic forwarding_started {false}; + +static int guest_forward(void* display, guest_long resourceid, int error_code, int request_code, int minor_code) { + forwarding_started = true; + forwarding_started.notify_one(); + return ForwardXError(static_cast(display), resourceid, error_code, request_code, minor_code); +} + +static int app_handler(Display* display, XErrorEvent* event) { + if (display == guest) { + guest_calls++; + app_serial = event->serial; + app_error = event->error_code; + app_minor = event->minor_code; + } + app_calls++; + return 0; +} + +static bool host_usable_from_other_thread() { + std::atomic done {false}; + std::thread other([&] { + XNoOp(host); + XSync(host, False); + done = true; + }); + for (int i = 0; i < 300 && !done; i++) { + usleep(10000); + } + if (!done) { + return false; + } + other.join(); + return true; +} + +int main(int argc, char** argv) { + XInitThreads(); + host = XOpenDisplay(nullptr); + guest = XOpenDisplay(nullptr); + if (!host || !guest) { + return 2; + } + x11_manager.displays[guest] = host; + pending_forward = guest_forward; + XSetErrorHandler(app_handler); + fexfn_impl_libGL_GL_SetGuestXErrorForward(0, 0); + + if (argc > 1) { + auto library = dlopen("libGL.so.1", RTLD_NOW | RTLD_LOCAL); + if (!library) { + return 3; + } + auto choose = reinterpret_cast(dlsym(library, "glXChooseFBConfig")); + auto get_proc = reinterpret_cast(dlsym(library, "glXGetProcAddressARB")); + auto query = reinterpret_cast(dlsym(library, "glXQueryExtension")); + auto destroy = reinterpret_cast(dlsym(library, "glXDestroyContext")); + if (!choose || !get_proc || !query || !destroy) { + return 4; + } + auto create = reinterpret_cast(get_proc( + reinterpret_cast("glXCreateContextAttribsARB"))); + if (!create) { + return 5; + } + int error_base, event_base, count; + if (!query(host, &error_base, &event_base)) { + return 6; + } + const int config_attribs[] = {GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, None}; + auto configs = choose(host, DefaultScreen(host), config_attribs, &count); + if (!configs || count == 0) { + return 7; + } + const int supported[] = {GLX_CONTEXT_MAJOR_VERSION_ARB, 2, GLX_CONTEXT_MINOR_VERSION_ARB, 1, None}; + auto initial = create(host, configs[0], nullptr, True, supported); + if (!initial) { + return 8; + } + destroy(host, initial); + if (strcmp(argv[1], "default") == 0) { + XSetErrorHandler(nullptr); + fexfn_impl_libGL_GL_SetGuestXErrorForward(0, 0); + } + const int unsupported[] = {GLX_CONTEXT_MAJOR_VERSION_ARB, 4, GLX_CONTEXT_MINOR_VERSION_ARB, 6, None}; + auto rejected = create(host, configs[0], nullptr, True, unsupported); + XSync(host, False); + auto fallback = create(host, configs[0], nullptr, True, supported); + printf("valid_config=1 rejected=%d guest_errors=%d bad_fbconfig=%d minor_zero=%d fallback=%d\n", + rejected == nullptr, guest_calls.load(), app_error == error_base + GLXBadFBConfig, + app_minor == 0, fallback != nullptr); + if (fallback) { + destroy(host, fallback); + } + XFree(configs); + fflush(stdout); + _exit(0); + } + + std::atomic guest_held {false}; + std::atomic host_reached {false}; + std::thread contender([&] { + XLockDisplay(guest); + guest_held = true; + forwarding_started.wait(false); + XNoOp(host); + XFlush(host); + host_reached = true; + XUnlockDisplay(guest); + }); + while (!guest_held) { + usleep(1000); + } + XFreePixmap(host, 1); + XSync(host, False); + contender.join(); + bool usable = host_usable_from_other_thread(); + printf("app_calls=%d guest_calls=%d host_reached=%d usable=%d serial_from_guest=%d\n", app_calls.load(), + guest_calls.load(), host_reached.load(), usable, app_serial != 0 && app_serial <= guest->request); + fflush(stdout); + _exit(0); +} +""" + + +def compile_cpp(source, output): + return subprocess.run(["c++", "-std=c++20", "-O1", "-Wall", "-Werror", "-pthread", "-o", str(output), str(source), "-lX11"], + capture_output=True, text=True) + + +@unittest.skipUnless(shutil.which("c++"), "needs c++") +class FexGlThunkErrorForwardTest(unittest.TestCase): + HARNESS_SOURCE = HARNESS + DEPENDENCY_HEADERS = ("X11/Xlibint.h",) + + @classmethod + def setUpClass(cls): + guest = added("ThunkLibs/libGL/libGL_Guest.cpp", "static int ForwardXError(", "\n}") + host = added("ThunkLibs/libGL/libGL_Host.cpp", "static XErrorHandler HostPreviousXErrorHandler", + " HostPreviousXErrorHandler = Previous;\n }\n}") + manager = "ThunkLibs/include/common/X11Manager.h" + mutex = added(manager, "std::", " mutex;") + forward = added(manager, "int (*GuestXErrorForward)", "= nullptr;") + find = added(manager, "_XDisplay* FindGuestDisplay(", " return nullptr;\n }") + cls.tmp = Path(tempfile.mkdtemp()) + cls.addClassCleanup(shutil.rmtree, cls.tmp) + probe = cls.tmp / "probe.cpp" + probe.write_text("".join(f"#include <{header}>\n" for header in cls.DEPENDENCY_HEADERS) + + "int main() { return 0; }\n") + if compile_cpp(probe, cls.tmp / "probe").returncode != 0: + raise unittest.SkipTest("needs the native development files for this harness") + source = cls.tmp / "harness.cpp" + source.write_text(cls.HARNESS_SOURCE.replace("MUTEX_SOURCE", mutex).replace("FORWARD_SOURCE", forward) + .replace("FIND_SOURCE", find).replace("GUEST_SOURCE", guest).replace("HOST_SOURCE", host)) + cls.program = cls.tmp / "harness" + result = compile_cpp(source, cls.program) + if result.returncode != 0: + raise AssertionError(result.stderr) + + def run_harness(self, *args): + try: + result = subprocess.run([str(self.program), *args], capture_output=True, text=True, timeout=10) + except subprocess.TimeoutExpired: + self.fail("the host error handler blocked") + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout.splitlines() + + def test_error_on_a_host_display_reaches_the_programs_handler(self): + owned = self.run_harness()[0] + self.assertIn("owned=7 app_calls=1 app_display_is_guest=1", owned) + self.assertIn("error=163 request=148 minor=0 resource=ffffffff", owned) + self.assertIn("handler_kept=1", owned) + + def test_forwarded_error_carries_the_programs_own_serial(self): + self.assertIn(" serial=44 ", self.run_harness()[0]) + + def test_forwarding_never_swaps_the_programs_handler(self): + self.assertIn("guest_set_calls=0", self.run_harness()[0]) + + def test_error_while_the_display_lock_is_held_does_not_block(self): + self.assertEqual(self.run_harness("reentry"), ["reentry=7 app_calls=1"]) + + def test_error_while_another_thread_holds_the_programs_display_lock_does_not_deadlock(self): + self.assertEqual(self.run_harness("crosslock"), ["crosslock=7 app_calls=1"]) + + def test_error_on_a_display_the_gl_thunk_does_not_own_keeps_the_previous_handler(self): + self.assertEqual(self.run_harness()[1], "foreign=3 previous_calls=1 previous_display_is_other=1") + + +@unittest.skipUnless(shutil.which("c++") and shutil.which("Xvfb"), "needs c++ and Xvfb") +class FexGlThunkErrorForwardRealXlibTest(FexGlThunkErrorForwardTest): + HARNESS_SOURCE = REAL_HARNESS + DEPENDENCY_HEADERS = ("GL/glx.h", "GL/glxext.h", "X11/Xmd.h", "GL/glxproto.h", "X11/Xlibint.h") + + @classmethod + def setUpClass(cls): + super().setUpClass() + read, write = os.pipe() + cls.server = subprocess.Popen(["Xvfb", "-displayfd", str(write), "-nolisten", "tcp", "-screen", "0", "64x64x24"], + pass_fds=(write,), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + os.close(write) + with os.fdopen(read) as stream: + number = stream.readline().strip() + if not number: + cls.server.kill() + cls.server.wait() + raise unittest.SkipTest("Xvfb did not start") + cls.display = ":" + number + + @classmethod + def tearDownClass(cls): + cls.server.terminate() + cls.server.wait() + + def run_real(self, *args, expected_returncode=0): + try: + result = subprocess.run([str(self.program), *args], capture_output=True, text=True, timeout=20, + env={**os.environ, "DISPLAY": self.display, "LIBGL_ALWAYS_SOFTWARE": "1", + "MESA_GL_VERSION_OVERRIDE": "4.5"}) + except subprocess.TimeoutExpired: + self.fail("the host error handler deadlocked") + self.assertEqual(result.returncode, expected_returncode, result.stderr) + return result.stdout.strip() + + def test_real_error_reaches_the_program_while_another_thread_holds_its_display(self): + self.assertEqual(self.run_real(), + "app_calls=1 guest_calls=1 host_reached=1 usable=1 serial_from_guest=1") + + def test_valid_config_with_unsupported_version_reaches_handler_and_allows_fallback(self): + self.assertEqual(self.run_real("glx"), + "valid_config=1 rejected=1 guest_errors=1 bad_fbconfig=1 minor_zero=1 fallback=1") + + def test_program_without_error_handler_keeps_default_fatal_behavior(self): + self.run_real("default", expected_returncode=1) + + test_error_on_a_host_display_reaches_the_programs_handler = None + test_forwarded_error_carries_the_programs_own_serial = None + test_forwarding_never_swaps_the_programs_handler = None + test_error_while_the_display_lock_is_held_does_not_block = None + test_error_while_another_thread_holds_the_programs_display_lock_does_not_deadlock = None + test_error_on_a_display_the_gl_thunk_does_not_own_keeps_the_previous_handler = None + + +class FexGlThunkDependencyProbeTest(unittest.TestCase): + def test_missing_glx_headers_skip_the_real_harness(self): + def compile_without_glx(source, output): + self.assertEqual(source.name, "probe.cpp") + self.assertIn("#include ", source.read_text()) + return subprocess.CompletedProcess([], 1, "", "missing GLX headers") + + with mock.patch(__name__ + ".compile_cpp", side_effect=compile_without_glx): + try: + with self.assertRaises(unittest.SkipTest): + FexGlThunkErrorForwardRealXlibTest.setUpClass() + finally: + FexGlThunkErrorForwardRealXlibTest.doClassCleanups() + + def test_real_harness_compile_errors_are_failures(self): + results = [subprocess.CompletedProcess([], 0, "", ""), + subprocess.CompletedProcess([], 1, "", "harness compile error")] + with mock.patch(__name__ + ".compile_cpp", side_effect=results): + try: + with self.assertRaisesRegex(AssertionError, "harness compile error"): + FexGlThunkErrorForwardRealXlibTest.setUpClass() + finally: + FexGlThunkErrorForwardRealXlibTest.doClassCleanups() + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_memory_pressure.py b/tools/tests/test_memory_pressure.py index 29a2008866..5dbb8d8d89 100644 --- a/tools/tests/test_memory_pressure.py +++ b/tools/tests/test_memory_pressure.py @@ -455,7 +455,7 @@ class ReclaimDispatchTest(unittest.TestCase): source = source.replace('/tmp/.bl-zram', str(root / 'ctl')) monitor = SCRIPT.read_text() start = monitor.index(' _bl_preserved_growth=$_bl_growth', monitor.index('while kill -0 $$')) - stop = monitor.index(' if [ "$_bl_game" = 1 ] && bl_game_focused', start) + stop = monitor.index(' _bl_focus=1\n', start) cycle = monitor[start:stop] if body is None else body script = f''' set -u diff --git a/tools/tests/test_steam_adopt.py b/tools/tests/test_steam_adopt.py new file mode 100644 index 0000000000..71f1ead653 --- /dev/null +++ b/tools/tests/test_steam_adopt.py @@ -0,0 +1,147 @@ +import importlib.machinery +import importlib.util +import runpy +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +APPINFO = runpy.run_path(str(Path(__file__).with_name("test_droiddeck_fex.py")))["AppInfoTest"].appinfo + + +def load(name): + loader = importlib.machinery.SourceFileLoader(name.replace("-", "_"), str(BIN / name)) + spec = importlib.util.spec_from_loader(loader.name, loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + return module + + +library = load("droiddeck-steam-library") + + +def record(kind, installdir, name): + return {"common": {"type": kind, "name": name}, "config": {"installdir": installdir}} + + +class AdoptTest(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + root = Path(temp.name) + self.steam = root / "Steam" + self.card = root / "card" + self.common = self.card / "steamapps/common" + self.common.mkdir(parents=True) + (self.steam / "appcache").mkdir(parents=True) + (self.steam / "steamapps").mkdir() + self.write_info({ + 10: record("Game", "Alpha", 'Alpha "Deluxe"'), + 20: record("Game", "Beta", "Beta"), + 30: record("Tool", "Proton Thing", "Proton Thing"), + 40: record("Game", "Shared", "Shared Game"), + 41: record("Demo", "Shared", "Shared Demo"), + 50: record("Game", "Twin", "Twin One"), + 51: record("Game", "Twin", "Twin Two"), + }) + for patcher in (patch.object(library, "BIN_DIR", str(BIN)), + patch("builtins.print")): + patcher.start() + self.addCleanup(patcher.stop) + + def write_info(self, apps): + (self.steam / "appcache/appinfo.vdf").write_bytes(APPINFO(apps)) + + def folder(self, name, files=("data.bin",)): + path = self.common / name + path.mkdir(parents=True, exist_ok=True) + for f in files: + (path / f).write_text("x") + + def manifest(self, app, root=None): + return (root or self.card) / ("steamapps/appmanifest_%s.acf" % app) + + def adopt(self): + return library.adopt(str(self.steam), str(self.card)) + + def test_matched_folder_gets_a_validating_manifest(self): + self.folder("Alpha") + self.assertEqual(self.adopt(), 1) + text = self.manifest(10).read_text() + for line in ('"appid" "10"', '"Universe" "1"', '"StateFlags" "4"', '"installdir" "Alpha"', + '"name" "Alpha \\"Deluxe\\""', '"AutoUpdateBehavior" "1"'): + self.assertIn(line, text) + self.assertNotIn("buildid", text) + self.assertNotIn("InstalledDepots", text) + + def test_existing_manifest_is_untouched(self): + self.folder("Alpha") + self.manifest(10).write_text("mine") + self.assertEqual(self.adopt(), 0) + self.assertEqual(self.manifest(10).read_text(), "mine") + + def test_unmatched_empty_and_hidden_folders_are_skipped(self): + self.folder("Unknown") + self.folder(".hidden") + (self.common / "Beta").mkdir() + (self.common / "file.txt").write_text("x") + self.assertEqual(self.adopt(), 0) + self.assertEqual(list((self.card / "steamapps").glob("appmanifest_*")), []) + + def test_unreadable_game_folder_is_skipped_without_aborting(self): + self.folder("Unreadable") + real = library.os.scandir + + def scandir(path): + if str(path).endswith("Unreadable"): + raise PermissionError(path) + return real(path) + + with patch.object(library.os, "scandir", scandir): + self.assertEqual(library.adoptable(str(self.card), set()), []) + + def test_tool_type_app_is_skipped(self): + self.folder("Proton Thing") + self.assertEqual(self.adopt(), 0) + self.assertFalse(self.manifest(30).exists()) + + def test_game_wins_over_demo_and_ambiguous_games_are_skipped(self): + self.folder("Shared") + self.folder("Twin") + self.assertEqual(self.adopt(), 1) + self.assertTrue(self.manifest(40).exists()) + self.assertFalse(self.manifest(41).exists()) + self.assertFalse(self.manifest(50).exists() or self.manifest(51).exists()) + + def test_app_installed_in_another_library_is_left_alone(self): + self.folder("Alpha") + other = self.steam / "steamapps/appmanifest_10.acf" + other.write_text('"AppState"\n{\n\t"appid"\t"10"\n\t"installdir"\t"Elsewhere"\n}\n') + self.assertEqual(self.adopt(), 0) + self.assertFalse(self.manifest(10).exists()) + self.assertEqual(len(list(self.steam.glob("steamapps/appmanifest_*"))), 1) + + def test_adoption_is_idempotent_and_only_touches_the_given_library(self): + self.folder("Alpha") + self.folder("Beta") + self.assertEqual(self.adopt(), 2) + first = {n: self.manifest(n).read_text() for n in (10, 20)} + self.assertEqual(self.adopt(), 0) + self.assertEqual({n: self.manifest(n).read_text() for n in (10, 20)}, first) + self.assertEqual(list(self.steam.glob("steamapps/appmanifest_*")), []) + + def test_main_adopts_every_registered_library(self): + self.folder("Beta") + listing = self.steam.parent / "libraries.json" + listing.write_text('[{"path": "%s", "label": "SD Card"}]' % self.card) + with patch.dict("os.environ", {"BL_STEAM_LIBRARIES": str(listing)}), \ + patch("sys.argv", ["droiddeck-steam-library", str(self.steam)]): + library.main() + self.assertTrue(self.manifest(20).exists()) + self.assertIn(str(self.card), (self.steam / "steamapps/libraryfolders.vdf").read_text()) + self.assertIn('"20"', (self.steam / "steamapps/libraryfolders.vdf").read_text()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_steam_games.py b/tools/tests/test_steam_games.py index 13235e68b4..08ffc90935 100644 --- a/tools/tests/test_steam_games.py +++ b/tools/tests/test_steam_games.py @@ -5,6 +5,7 @@ import os from pathlib import Path import shutil import subprocess +import runpy import tempfile import unittest import zlib @@ -26,6 +27,15 @@ shortcuts = load('droiddeck-steam-shortcuts') library = load('droiddeck-steam-library') +class ManifestTextTest(unittest.TestCase): + def test_minimal_and_bare_text_is_exact(self): + build = runpy.run_path(str(BIN / 'steam-compatibility'))['manifest_text'] + minimal = ('"AppState"\n{\n "appid" "7"\n "Universe" "1"\n "name" "A \\"B\\" C D"\n' + ' "StateFlags" "4"\n "installdir" "DroidDeck-7"\n}\n') + self.assertEqual(minimal, build(7, 'A "B"\nC\rD', 'DroidDeck-7')) + self.assertEqual(minimal[:-2] + ' "AutoUpdateBehavior" "1"\n}\n', build(7, 'A "B"\nC\rD', 'DroidDeck-7', True)) + + class ImportsTest(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() diff --git a/tools/tests/test_store_launch.py b/tools/tests/test_store_launch.py index 36a1b7c9a1..ce7c33e305 100644 --- a/tools/tests/test_store_launch.py +++ b/tools/tests/test_store_launch.py @@ -1,6 +1,8 @@ import importlib.machinery import importlib.util import json +import shlex +import subprocess import os from pathlib import Path import tempfile @@ -317,6 +319,33 @@ class Launchers(unittest.TestCase): self.assertIn('bl_store_launch() {', compat.BL_STORE_SETUP) self.assertIn('waitforexitandrun', compat.BL_STORE_SETUP) + def run_store_game(self, game, store_exit=True): + with tempfile.TemporaryDirectory() as root: + hook = Path(root) / 'hook' + record = Path(root) / 'exited' + hook.write_text('#!/bin/sh\necho "$@" > "%s"\n' % record) + hook.chmod(0o755) + setup = compat.BL_STORE_SETUP.replace('/usr/local/bin/droiddeck-store-launch --exited', str(hook) + ' --exited') + script = setup + '\nBL_STORE_ARGS=(game.bat)\n%sbl_run sh -c %s\nexit 99\n' % ( + 'BL_STORE_EXIT=1\n' if store_exit else '', shlex.quote(game)) + done = subprocess.run(['bash', '-c', script], start_new_session=True, timeout=20) + return done.returncode, record.read_text().split() if record.exists() else None + + def test_a_store_game_ended_by_a_group_signal_still_reports_its_exit(self): + for signal_name, code in (('INT', '130'), ('TERM', '143'), ('HUP', '129')): + rc, hook = self.run_store_game('kill -%s 0; sleep 5' % signal_name) + self.assertEqual(['--exited', '--code', code, 'game.bat'], hook, signal_name) + self.assertEqual(int(code), rc, signal_name) + + def test_a_store_game_that_exits_by_itself_reports_its_code_once(self): + self.assertEqual((3, ['--exited', '--code', '3', 'game.bat']), self.run_store_game('exit 3')) + + def test_other_games_still_replace_the_wrapper_without_the_exit_hook(self): + self.assertEqual((4, None), self.run_store_game('exit 4', store_exit=False)) + rc, hook = self.run_store_game('kill -INT 0; sleep 5', store_exit=False) + self.assertIsNone(hook) + self.assertEqual(-2, rc) + if __name__ == '__main__': unittest.main() diff --git a/tools/tests/test_store_launch_rockstar.py b/tools/tests/test_store_launch_rockstar.py index fe7d808f2a..e17fa7b30b 100644 --- a/tools/tests/test_store_launch_rockstar.py +++ b/tools/tests/test_store_launch_rockstar.py @@ -6,7 +6,7 @@ import time import unittest from unittest.mock import patch -from test_store_launch import store +from test_store_launch import game, store class RockstarLaunch(unittest.TestCase): @@ -217,6 +217,70 @@ class RockstarLaunch(unittest.TestCase): self.assertEqual([], requests) self.assertFalse(config.exists()) + def test_each_launch_starts_a_fresh_launcher_log(self): + with tempfile.TemporaryDirectory() as root: + stale = [] + + def ask(channel, request, timeout): + stale.append((config.parent / 'launcher.log').exists()) + return answer + + folder, sidecar, prefix, service, answer = self.setup_game(root) + config = prefix / 'pfx' / store.ROCKSTAR_FOLDER / 'launch.json' + config.parent.mkdir(parents=True) + (config.parent / 'launcher.log').write_bytes(b'x' * 70000) + with patch.object(store, 'ROCKSTAR_SERVICE', service), patch.object(store, 'rockstar_registry', return_value=True): + result = store.prepare_rockstar(folder, sidecar, str(prefix), str(Path(root) / 'channel'), ask_app=ask) + self.assertEqual('ready', result) + self.assertEqual([False], stale) + + def exit_game(self, root, store_id, log_text=None, link=None): + folder = game(root, store_id=store_id, ident='gta5') + prefix = Path(root) / 'prefix' + target = prefix / 'pfx' / store.ROCKSTAR_FOLDER + target.mkdir(parents=True) + if log_text is not None: + (target / 'launcher.log').write_text(log_text) + if link is not None: + (target / 'launcher.log').symlink_to(link) + lines = [] + with patch.dict(os.environ, {'BL_LAUNCH_DIR': str(Path(root) / 'session'), 'STEAM_COMPAT_DATA_PATH': str(prefix)}), \ + patch.object(store, 'ask', return_value={'ok': True}), patch.object(store, 'log', lines.append): + self.assertEqual(0, store.main(['--exited', str(folder / '.droiddeck-launch.bat')])) + return lines, target / 'launcher.log' + + def test_launcher_log_reaches_the_session_log_when_the_game_exits(self): + with tempfile.TemporaryDirectory() as root: + text = 'launch handoff accepted\r\nlauncher pipes created, identity: none\r\n\r\ngame exited with code 0\r\n' + lines, path = self.exit_game(root, 'rockstar', log_text=text) + self.assertEqual(['rockstar launcher: launch handoff accepted', + 'rockstar launcher: launcher pipes created, identity: none', + 'rockstar launcher: game exited with code 0'], lines) + self.assertFalse(path.exists()) + + def test_launcher_log_relay_does_not_follow_links(self): + with tempfile.TemporaryDirectory() as root: + outside = Path(root) / 'outside.txt' + outside.write_text('private\n') + lines, path = self.exit_game(root, 'rockstar', link=outside) + self.assertEqual([], lines) + self.assertTrue(path.is_symlink()) + self.assertEqual('private\n', outside.read_text()) + + def test_other_stores_do_not_relay_the_launcher_log(self): + with tempfile.TemporaryDirectory() as root: + lines, path = self.exit_game(root, 'gog', log_text='launch handoff accepted\n') + self.assertFalse(any(line.startswith('rockstar launcher:') for line in lines)) + self.assertTrue(path.exists()) + + def test_relay_is_bounded(self): + with tempfile.TemporaryDirectory() as root: + prefix = Path(root) / 'prefix' + target = prefix / 'pfx' / store.ROCKSTAR_FOLDER + target.mkdir(parents=True) + (target / 'launcher.log').write_text('a' * 10 + '\n' + 'b' * 100 + '\n') + self.assertEqual(['a' * 10, 'b' * 5], store.rockstar_launcher_log(str(prefix), limit=16)) + def test_writes_both_registry_views_and_escapes_values(self): with tempfile.TemporaryDirectory() as root: folder, _, prefix, _, _ = self.setup_game(root) diff --git a/tools/tests/test_zram_preload.py b/tools/tests/test_zram_preload.py index 88d5c73020..59bc500ee4 100644 --- a/tools/tests/test_zram_preload.py +++ b/tools/tests/test_zram_preload.py @@ -1,5 +1,6 @@ import os from pathlib import Path +import signal import shutil import subprocess import tempfile @@ -9,6 +10,7 @@ PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" PROGRAM = r""" #define _GNU_SOURCE +#include #include #include #include @@ -17,12 +19,36 @@ PROGRAM = r""" #include #include #include +#include +#include +#include #include static const char *ctl; static size_t size, page; static volatile int stop; static unsigned char *shared; +static volatile sig_atomic_t urg_tid; +static volatile sig_atomic_t usr_tid; +static int urg_count, usr_count; +static int worker_tid; +static int worker_delivery; + +_Static_assert(__atomic_always_lock_free(sizeof(int), 0), "signal state must be lock-free"); + +static void signal_tid(int sig) { + sig_atomic_t tid = (sig_atomic_t)syscall(SYS_gettid); + if (tid == __atomic_load_n(&worker_tid, __ATOMIC_RELAXED)) + __atomic_store_n(&worker_delivery, 1, __ATOMIC_RELAXED); + if (sig == SIGURG) { + __atomic_store_n(&urg_tid, tid, __ATOMIC_RELAXED); + __atomic_add_fetch(&urg_count, 1, __ATOMIC_RELEASE); + } + if (sig == SIGUSR1) { + __atomic_store_n(&usr_tid, tid, __ATOMIC_RELAXED); + __atomic_add_fetch(&usr_count, 1, __ATOMIC_RELEASE); + } +} static long status(const char *key) { FILE *f = fopen("/proc/self/status", "r"); @@ -34,13 +60,37 @@ static long status(const char *key) { return v; } -static void request(char mode) { +static void send_request(char mode) { int fd = open(ctl, O_WRONLY | O_TRUNC); if (fd < 0 || write(fd, &mode, 1) != 1) exit(3); close(fd); kill(getpid(), SIGURG); } +static void wait_ack(void) { + char ack[256]; + snprintf(ack, sizeof(ack), "%s.ack.%d", ctl, getpid()); + for (int i = 0; i < 1200; i++) { + FILE *f = fopen(ack, "r"); + int done = 0; + if (f) { + done = fgetc(f) == '1'; + fclose(f); + } + if (done) return; + usleep(10000); + } + exit(5); +} + +static void request(char mode) { + send_request(mode); + if (mode == '1') { + wait_ack(); + } + usleep(1000000); +} + static uint64_t sum(const unsigned char *p, size_t n) { uint64_t s = 0; for (size_t i = 0; i < n; i += 64) s = s * 31 + p[i]; @@ -77,6 +127,106 @@ int main(int argc, char **argv) { sigaction(SIGURG, NULL, &sa); printf("handler %d\n", (sa.sa_flags & SA_SIGINFO) ? 1 : 0); if (argc > 4) { + if (!strcmp(argv[4], "signals")) { + struct sigaction signal_action; + memset(&signal_action, 0, sizeof(signal_action)); + signal_action.sa_handler = signal_tid; + sigemptyset(&signal_action.sa_mask); + sigaction(SIGURG, &signal_action, NULL); + sigaction(SIGUSR1, &signal_action, NULL); + printf("ready %d\n", getpid()); + fflush(stdout); + int id; + if (scanf("%d", &id) != 1) return 10; + __atomic_store_n(&worker_tid, id, __ATOMIC_RELAXED); + printf("armed 1\n"); + fflush(stdout); + for (int round = 1; round <= 100; round++) { + int i; + for (i = 0; i < 5000 && + (__atomic_load_n(&urg_count, __ATOMIC_ACQUIRE) < round || + __atomic_load_n(&usr_count, __ATOMIC_ACQUIRE) < round); i++) usleep(1000); + if (i == 5000) return 11; + printf("received %d\n", round); + fflush(stdout); + } + stop = 1; + for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); + printf("urg %d\n", __atomic_load_n(&urg_tid, __ATOMIC_RELAXED)); + printf("usr %d\n", __atomic_load_n(&usr_tid, __ATOMIC_RELAXED)); + printf("worker %d\n", __atomic_load_n(&worker_delivery, __ATOMIC_RELAXED)); + return 0; + } else if (!strcmp(argv[4], "fork")) { + pid_t child = fork(); + if (child < 0) exit(6); + if (child == 0) { + request('0'); + request('1'); + _exit(0); + } + int status_code; + waitpid(child, &status_code, 0); + printf("childack %d\n", WIFEXITED(status_code) && WEXITSTATUS(status_code) == 0); + } else if (!strcmp(argv[4], "burst")) { + send_request('0'); + usleep(10000); + send_request('1'); + wait_ack(); + printf("burstack 1\n"); + } else if (!strcmp(argv[4], "timed-inline") || !strcmp(argv[4], "timed-inline-single")) { + pid_t child = fork(); + if (child < 0) exit(8); + if (child == 0) { + if (!strcmp(argv[4], "timed-inline-single")) { + if (munmap(data, size) || munmap(shared, size)) _exit(12); + data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + shared = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (data == MAP_FAILED || shared == MAP_FAILED) _exit(13); + for (size_t i = 0; i < size; i++) data[i] = (unsigned char)(i * 7 + i / 4096); + memset(shared, 0, size); + } + struct timespec start, end; + int fd = open(ctl, O_WRONLY | O_TRUNC); + if (fd < 0 || write(fd, "1", 1) != 1) _exit(9); + close(fd); + clock_gettime(CLOCK_MONOTONIC, &start); + int requests = !strcmp(argv[4], "timed-inline-single") ? 1 : 64; + for (int i = 0; i < requests; i++) { + send_request('1'); + } + clock_gettime(CLOCK_MONOTONIC, &end); + long elapsed = (end.tv_sec - start.tv_sec) * 1000L + + (end.tv_nsec - start.tv_nsec) / 1000000L; + printf("inline %ld\n", elapsed); + printf("inline_swap %ld\n", status("VmSwap:")); + fflush(stdout); + _exit(0); + } + int status_code; + if (waitpid(child, &status_code, 0) != child || !WIFEXITED(status_code) || WEXITSTATUS(status_code)) exit(14); + } else if (!strcmp(argv[4], "timed")) { + struct timespec previous, current, deadline; + long max_gap = 0; + int fd = open(ctl, O_WRONLY | O_TRUNC); + if (fd < 0 || write(fd, "1", 1) != 1) exit(7); + close(fd); + clock_gettime(CLOCK_MONOTONIC, &previous); + kill(getpid(), SIGURG); + deadline = previous; + deadline.tv_sec += 1; + for (;;) { + clock_gettime(CLOCK_MONOTONIC, ¤t); + long gap = (current.tv_sec - previous.tv_sec) * 1000L + + (current.tv_nsec - previous.tv_nsec) / 1000000L; + if (gap > max_gap) max_gap = gap; + previous = current; + if (current.tv_sec > deadline.tv_sec || + (current.tv_sec == deadline.tv_sec && current.tv_nsec >= deadline.tv_nsec)) break; + } + wait_ack(); + printf("gap %ld\n", max_gap); + printf("out %ld\n", status("VmSwap:")); + } else { unsigned char *ro = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); memset(ro, 0x5a, size); mprotect(ro, size, PROT_READ); @@ -84,6 +234,7 @@ int main(int argc, char **argv) { printf("elsewhere %ld\n", status("VmSwap:")); request('0'); printf("back %ld\n", status("VmSwap:")); + } } for (int c = 0; c < cycles; c++) { request('1'); @@ -173,6 +324,72 @@ class ZramPreloadTest(unittest.TestCase): self.assertEqual([1], out["intact"]) self.assertEqual(6, len(out["out"])) + def test_process_signals_do_not_reach_zram_worker(self): + environment = dict(os.environ, LD_PRELOAD=str(self.lib)) + process = subprocess.Popen([str(self.steam), str(self.ctl), "1", "0", "signals"], + env=environment, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) + try: + process.stdout.readline() + ready = process.stdout.readline().split() + self.assertEqual("ready", ready[0]) + worker = None + task_dir = Path("/proc") / ready[1] / "task" + for task in task_dir.iterdir(): + if (task / "comm").read_text().strip() == "zr-worker": + worker = int(task.name) + break + self.assertIsNotNone(worker) + self.assertEqual(os.sched_getscheduler(process.pid), os.sched_getscheduler(worker)) + process.stdin.write(f"{worker}\n") + process.stdin.flush() + self.assertEqual("armed 1", process.stdout.readline().strip()) + for _ in range(100): + os.kill(process.pid, signal.SIGURG) + os.kill(process.pid, signal.SIGUSR1) + self.assertEqual(f"received {_ + 1}", process.stdout.readline().strip()) + output, _ = process.communicate(timeout=10) + values = dict(line.split() for line in output.splitlines()) + self.assertNotEqual(0, int(values["urg"])) + self.assertNotEqual(0, int(values["usr"])) + self.assertEqual(0, int(values["worker"])) + self.assertNotEqual(worker, int(values["urg"])) + self.assertNotEqual(worker, int(values["usr"])) + finally: + if process.poll() is None: + process.kill() + process.wait() + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_signal_does_not_stall_the_main_thread(self): + out = self.run_program(None, 256, 0, "timed") + self.assertLess(out["gap"][0], 250) + self.assertGreater(out["out"][0], 32 * 1024) + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_inline_pageout_exceeds_async_timing_tolerance(self): + out = self.run_program(None, 256, 0, "timed-inline") + self.assertGreater(out["inline"][0], 250) + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_single_request_timing_control(self): + asynchronous = self.run_program(None, 48, 0, "timed") + self.assertGreater(asynchronous["out"][0], 32 * 1024) + inline = self.run_program(None, 48, 0, "timed-inline-single") + self.assertGreater(inline["inline_swap"][0], 32 * 1024) + if inline["inline"][0] <= 250: + self.skipTest("single inline request did not establish the 250 ms timing threshold") + self.assertGreater(inline["inline"][0], 250) + self.assertLess(asynchronous["gap"][0], 250) + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_forked_child_still_acknowledges_pageout(self): + out = self.run_program(None, 48, 0, "fork") + self.assertEqual([1], out["childack"]) + + def test_worker_acknowledges_back_to_back_requests(self): + out = self.run_program(None, 48, 0, "burst") + self.assertEqual([1], out["burstack"]) + if __name__ == "__main__": unittest.main()