Compare commits

..
Author SHA1 Message Date
The412Banner 14b007ab9f fix(display): a nested compositor keeps composing its overlays on a rotated display, so the picture stops strobing 2026-11-29 00:34:15 +00:00
measlesbagel b09e2f9ba7 fix(bionic): pack GStreamer's debug plugin, so game videos play (#3294)
winegstreamer puts a capssetter, from the debug plugin, at the front of
every video stream's conversion chain. Wine creates it by name at run
time, so check-needed.py, which follows linked libraries, could not
catch the missing plugin, and those videos played nothing on Bionic.
2026-11-28 18:07:50 -05:00
The412Banner 1a22d2a1be feat(bionic): build DroidDeck-Bionic on the DroidDeck-Proton 11-14.1 Wine layer (#3389)
The tool still packed the 12.8 layer (v16-unwind). The v18 layer is the build
of DroidDeck-Proton 11-14.1 Bannerlator ships: Valve Wine a47c73f52fd7, the
GE-Proton11-14 picks, and the ARM64EC code-map and unwind fixes 12.8 carried.
Same layout as 12.8 (three more files), so only the pin changes. Tools are
named DroidDeck-Bionic-14.1-rN; the app's version compare offers 14.1 over 12.8.
2026-11-28 18:01:15 -05:00
xlulx ecaec5da01 fix(bionic): run games from a DroidDeck-Proton prefix that start through a launcher (#3336)
* fix(bionic): run games from a DroidDeck-Proton prefix that start through a launcher

Europa Universalis IV, moved from DroidDeck-Proton to DroidDeck-Bionic, never got past its launcher:

- The network adapter list (GetAdaptersAddresses) never answered with the layer's default if_nameindex code, so the
  Paradox Launcher waited forever. launch.sh sets WINE_NEW_NDIS=1 (the layer's getifaddrs code); a game's
  environment can still set 0.
- The game reported "Steam not detected": the prefix still named Proton's steam.exe (PID 0x20) as Steam's running
  client, and here that PID is the program Steam started, which quits after starting the game. launch.sh writes
  the PID this tool's own prefixes carry (0xfffe) before Wine starts.
- Its Workshop mod was missing: DroidDeck-Proton's s: drive names the guest path of the Steam library, which this
  Wine cannot follow. proton gives the prefix's guest drive links their Android paths for the launch; a session's
  start gives them their guest paths back.

* fix(bionic): give each launch its own temporary file for the registry and drive rewrites
2026-11-28 17:40:46 -05:00
MaxsTechReview a8aafad145 fix(session): the in-game menu opens on the first back tap and scrolls smoothly over a game (#3353)
* Open the session menu on the first back tap instead of after the double-tap window

* Hold the GPU clock up while a session panel is open over the game

* Keep the double back tap working after the first tap opens the menu

The first tap opens the menu at once, and opening the menu cleared the
pending tap, so a second tap closed the menu instead of opening Steam's
quick menu. The tap that opened the menu now keeps its window, and a
second back press inside it goes to the double-tap action.

Outside Steam both taps toggle the menu, so a double tap no longer opens
and then closes it.

* fix(session): drop pending back taps on focus loss and departure

* fix(session): drop pending back taps when the drawer closes or another panel opens

* fix(session): drop the quick-menu input's pending tap when the drawer closes

* fix(session): keep a back press already down when the drawer closes
2026-11-28 17:33:36 -05:00
ReVanTisandmaxjivi05 1d4eb2446e fix(input): a captured touchpad drives the pointer (#2802)
* fix(input): a captured touchpad drives the pointer

Android reports a captured touchpad's events as SOURCE_TOUCHPAD with the
finger positions on the pad and the movement in AXIS_RELATIVE_X/Y. The
capture handler only accepted SOURCE_MOUSE_RELATIVE, so every captured
touchpad event was dropped and the touchpad stopped working in a session.

Read the relative axes for a captured touchpad, and count a touchpad as
an attached pointer for the Auto relative mouse choice and for pointer
capture. A touchpad that declares SOURCE_TOUCHPAD is not captured for the
whole session, so Android keeps its cursor and gestures until a game holds
the pointer.

* fix(input): keep captured touchpad motion without relative axes

Some builds do not provide AXIS_RELATIVE_X/Y for a captured touchpad
(the AOSP include_relative_axis_values_for_captured_touchpads flag can
leave them out). Fall back to the movement between the pointer's
successive absolute positions, tracked per pointer id, and clear the
positions when capture changes or the pointer ends.

* fix(input): key captured touchpad positions by device too

A pointer id is only unique within its device, so the fallback positions
could collide between two touchpads or a replaced device. Key them by
device id and pointer id, and cover it with a test.

* fix(input): end only the touchpad that lifted

ACTION_UP and ACTION_CANCEL cleared every device's fallback positions.
Forget only the device that ended, so a second touchpad keeps its
baseline; a capture change still resets all of them.

* Give a captured touchpad taps, two-finger scroll and clickpad presses

* Keep captured touchpad clicks apart from mouse buttons

A tap's synthetic release shared the mouse's held-button owner, so it
could release a mouse button that was still held. Captured touchpad
presses now use their own owner, released when capture ends. A physical
pad press also keeps a later second finger from turning into a
right-click tap.

* Keep physical touchpad buttons on the mouse owner

A press made before capture was released under the captured owner and
stayed held. Physical buttons now always use the mouse owner, and only
gesture clicks use the touchpad owner. A physical press also releases a
pending tap click first, so the two never merge.

---------

Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-28 16:42:01 -05:00
25 changed files with 853 additions and 461 deletions

No files matched your search

@@ -334,7 +334,8 @@ extern void droiddeck_on_overlay_planes(int planes);
static int g_overlay_planes_told = -1;
static void tell_overlay_planes(void) {
const int planes = (g_zero_copy && g_display_buffer_driver) ? (sc_layer_overlay_affordable() ? 1 : 0) : -1;
const int composing = g_overlay_planes_told == 0 && vkp_surface_rotation_degrees() > 0;
const int planes = (g_zero_copy && g_display_buffer_driver) ? (sc_layer_overlay_affordable() && !composing ? 1 : 0) : -1;
if (planes == g_overlay_planes_told) return;
g_overlay_planes_told = planes;
droiddeck_on_overlay_planes(planes);
@@ -450,13 +450,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
return true
}
private val uiHandler = Handler(Looper.getMainLooper())
private var pendingBackAction: Runnable? = null
private var backTapOpenedDrawer = false
private val backTapsAtOnce: Boolean get() = SessionState.mode != SessionService.MODE_STEAM || !backActionsInverted
private val backTaps = com.droiddeck.launcher.input.BackTaps(
windowMs = { backDoubleTapMs.toLong() },
atOnce = { backTapsAtOnce },
onTap = { performBackAction(double = it) },
sameAction = { SessionState.mode != SessionService.MODE_STEAM },
)
private val backQamInput = com.droiddeck.launcher.input.BackQamInput(
setPressed = { padBridge?.setBackQamPressed(it) },
onTap = { performBackAction(double = it) },
doubleTapMs = { backDoubleTapMs.toLong() },
onCancel = { padBridge?.cancelBackQam() },
holds = { backHold },
atOnce = { backTapsAtOnce },
sameAction = { SessionState.mode != SessionService.MODE_STEAM },
)
private val mouseBackInput = com.droiddeck.launcher.input.MouseBackInput(
sendRight = { down -> heldButtons.set(32, PointerGestures.BTN_RIGHT, down) },
@@ -904,6 +913,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onCapturedPointer(event) || super.dispatchCapturedPointerEvent(event)
override fun dispatchPointerCaptureChanged(hasCapture: Boolean) {
super.dispatchPointerCaptureChanged(hasCapture)
capturedTouchpad.cancel()
heldButtons.release(64)
Log.i(TAG, "pointer capture " + if (hasCapture) "on" else "off")
if (hasCapture) {
pointerCaptureRefused = false
@@ -1127,11 +1138,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
when {
::loading.isInitialized && loading.ended -> finish()
inputSettingsOpen -> inputSettingsOpen = false
dockedTouchOnly -> routeBackAction()
dockedTouchOnly || backTaps.pending -> backTaps.tap()
drawerOpen -> drawerOpen = false
achievementsOpen -> closeAchievements()
pcKeyboardOpen -> pcKeyboardOpen = false
else -> routeBackAction()
else -> backTaps.tap()
}
}
})
@@ -1328,8 +1339,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
LaunchedEffect(drawerOpen, menuOwnsController, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) {
updateOnScreenControls()
padBridge?.setInputEnabled(resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended)
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || inputSettingsOpen || pipUi || appTextFocus || SessionState.suspended) {
backQamInput.cancel()
if (!drawerOpen && backTapOpenedDrawer) {
backTaps.cancel()
backQamInput.cancelTap()
backTapOpenedDrawer = false
}
val otherPanel = pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || inputSettingsOpen || pipUi || appTextFocus || SessionState.suspended
if (drawerOpen || otherPanel) {
if (otherPanel || !backTapOpenedDrawer) backTaps.cancel()
backQamInput.cancel(keepTap = backTapOpenedDrawer && !otherPanel)
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this@SessionActivity)
cancelTouchGestures()
}
@@ -1383,7 +1401,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (drawerOpen) {
syncLossless()
if (menuOwnsController) {
releasePads()
releasePads(keepBackTap = backTapOpenedDrawer)
androidx.compose.runtime.withFrameNanos { }
val requested = focusDrawer()
Log.i(TAG, "drawer root focus requested=$requested docked=$drawerDocked")
@@ -1422,6 +1440,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
LaunchedEffect(pcKeyboardOpen, drawerOpen, achievementsOpen) {
if (pcKeyboardOpen || drawerOpen || achievementsOpen) padMouse.reset()
}
val panelShown = panelOverGame
LaunchedEffect(panelShown) { boostGpuClock(panelShown && resumed) }
if (pcKeyboardOpen) com.droiddeck.launcher.ui.PcKeyboard(
sendKey = { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down, 32) },
onAndroidKeyboard = { pcKeyboardOpen = false; togglePrimaryKeyboard() },
@@ -2116,25 +2136,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
unfoldedPanel?.reload()
}
private fun routeBackAction() {
pendingBackAction?.let { pending ->
uiHandler.removeCallbacks(pending)
pendingBackAction = null
performBackAction(double = true)
return
}
val pending = Runnable {
pendingBackAction = null
performBackAction(double = false)
}
pendingBackAction = pending
uiHandler.postDelayed(pending, backDoubleTapMs.toLong())
}
private fun performBackAction(double: Boolean) {
val isSteam = SessionState.mode == SessionService.MODE_STEAM
val opensQam = isSteam && (double xor backActionsInverted)
if (opensQam) triggerSteamQam() else if (!dockedTouchOnly) drawerOpen = !drawerOpen
if (opensQam) triggerSteamQam() else if (!dockedTouchOnly) {
drawerOpen = !drawerOpen
backTapOpenedDrawer = drawerOpen && !double
}
}
private fun handleHomeGuideIntent(incoming: Intent?) {
@@ -2619,6 +2627,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun gpuClockHeld() = SessionPrefs.gpuClockPin(this) && !GpuClockPin.failed
private val panelOverGame: Boolean get() = ((drawerOpen && !drawerDocked) || achievementsOpen || gestureSettingsOpen || inputSettingsOpen) && !pipUi
private fun boostGpuClock(on: Boolean) {
if (!GpuClockPin.boost(on)) return
Thread { GpuClockPin.sync(applicationContext)?.let { Log.i(TAG, it) } }.start()
}
private fun readPrefs() {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
unfoldedControls = SessionPrefs.unfoldedControls(this)
@@ -3487,11 +3502,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
focusEndedScreen()
}
private fun releasePads() {
private fun releasePads(keepBackTap: Boolean = false) {
inputMotion.stop()
physicalInputBindings?.release()
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this)
backQamInput.cancel()
backQamInput.cancel(keepTap = keepBackTap)
padBridge?.releaseAll()
joyConVr?.releaseButtons()
}
@@ -3651,8 +3666,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
!pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen,
steam = SessionState.mode == SessionService.MODE_STEAM,
) { action ->
pendingBackAction?.let(uiHandler::removeCallbacks)
pendingBackAction = null
backTaps.cancel()
if (!dockedMenuIdle) drawerControllerActive = true
Log.i(TAG, "physical shortcut ${action.name} device=${event.deviceId} key=${event.keyCode} scan=${event.scanCode}")
when (action) {
@@ -3684,16 +3698,23 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
if (mouseBackHandled) return true
val backToQam = !pipUi && !appTextFocus && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen &&
val backToQam = !pipUi && !appTextFocus && (!menuOwnsController || backQamInput.awaitingTap) && !pcKeyboardOpen && !achievementsOpen &&
!inputSettingsOpen && !gestureSettingsOpen &&
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
!SessionState.suspended && padBridge?.canHoldQam() == true
if (backQamInput.onKeyEvent(event, backToQam)) {
pendingBackAction?.let(uiHandler::removeCallbacks)
pendingBackAction = null
backTaps.cancel()
return true
}
if (pipUi) return true
if (event.keyCode == KeyEvent.KEYCODE_BACK && backTapOpenedDrawer && backTaps.pending) {
when {
event.action == KeyEvent.ACTION_DOWN -> backTaps.hold()
event.action == KeyEvent.ACTION_UP && !event.isCanceled -> backTaps.tap()
event.action == KeyEvent.ACTION_UP -> backTaps.cancel()
}
return true
}
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
if (pad !== event) return dispatchKeyEvent(pad)
val fromController = PadBridge.isControllerKeyEvent(event)
@@ -3836,7 +3857,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
else -> return super.dispatchGenericMotionEvent(event)
}
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) && !drawerOpen) {
if ((event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) ||
event.isFromSource(android.view.InputDevice.SOURCE_TOUCHPAD)) && !drawerOpen) {
if (appUiOwnsPointer()) {
if (super.dispatchGenericMotionEvent(event)) return true
if (touchEditorOpen) return false
@@ -4020,7 +4042,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
steamSession = SessionState.mode == SessionService.MODE_STEAM,
steamDesktopUi = SessionState.steamUi == "desktop",
)) == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD
val mode = com.droiddeck.launcher.input.TouchGestureConfig.gamescopeRelativeMouse(wanted, mouseAttached(), touchpadRoute)
val mode = com.droiddeck.launcher.input.TouchGestureConfig.gamescopeRelativeMouse(wanted, pointerAttached(), touchpadRoute)
if (appliedRelativeMouseMode == mode) return
if (AgentGuest.setGamescopeConvar(this, "relative_mouse", mode)) appliedRelativeMouseMode = mode
else if (relativeMouseRetries++ < RELATIVE_MOUSE_MAX_RETRIES) uiHandler.postDelayed({ requestRelativeMouse() }, 2_000)
@@ -4151,6 +4173,27 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
private val capturedTouchpadListener: PointerGestures.Listener = object : PointerGestures.Listener by pointerListener {
override fun onMove(x: Float, y: Float) {
val rect = drawnRect() ?: return
val scale = sceneScale(rect)
capturedTouchpad.place(CAPTURED_PAD_CENTRE, CAPTURED_PAD_CENTRE)
onRelativeMouse((x - CAPTURED_PAD_CENTRE) * scale, (y - CAPTURED_PAD_CENTRE) * scale)
}
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
heldButtons.set(64, button, pressed)
}
override fun onThreeFingerTap(): Boolean = false
}
private val capturedTouchpad: TouchpadGestures by lazy {
TouchpadGestures(PointerGestures.slop(this), capturedTouchpadListener, holdDrags = false).apply {
bounds = android.graphics.RectF(0f, 0f, CAPTURED_PAD_CENTRE * 2f, CAPTURED_PAD_CENTRE * 2f)
place(CAPTURED_PAD_CENTRE, CAPTURED_PAD_CENTRE)
}
}
private val capturedPadMatrix = android.graphics.Matrix()
private val scrollListener = object : ScrollTouchGestures.Listener {
override fun onMove(x: Float, y: Float) {
val rect = pointerSurfaceRect() ?: return
@@ -5327,7 +5370,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun handleTouch(event: MotionEvent): Boolean {
val pen = PenStream.penIndex(event)
val penRouted = if (pen >= 0) routePen(event, pen).takeIf { it != PenRouter.Route.TOUCH } else null
if (penRouted == null && event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) return onMouse(event)
if (penRouted == null && (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) ||
event.isFromSource(android.view.InputDevice.SOURCE_TOUCHPAD))) return onMouse(event)
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
sessionTouchDown = true
@@ -5573,7 +5617,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun isHardwareMouse(d: InputDevice?): Boolean =
d != null && !d.isVirtual && !d.supportsSource(InputDevice.SOURCE_STYLUS) &&
(d.supportsSource(InputDevice.SOURCE_MOUSE) || d.supportsSource(InputDevice.SOURCE_MOUSE_RELATIVE))
(d.supportsSource(InputDevice.SOURCE_MOUSE) || d.supportsSource(InputDevice.SOURCE_MOUSE_RELATIVE) ||
d.supportsSource(InputDevice.SOURCE_TOUCHPAD))
private fun isTouchpad(d: InputDevice?): Boolean =
d?.supportsSource(InputDevice.SOURCE_TOUCHPAD) == true
/** Android also sends the Back and Forward buttons as key events, so they are handled as keys. */
private fun guestMouseButton(actionButton: Int): Int? = when (actionButton) {
@@ -5583,9 +5631,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
else -> PointerGestures.BTN_LEFT
}
private fun pointerAttached(): Boolean = usbMouse.active || InputDevice.getDeviceIds().any { id ->
isHardwareMouse(InputDevice.getDevice(id))
}
private fun mouseAttached(): Boolean = usbMouse.active || InputDevice.getDeviceIds().any { id ->
val d = InputDevice.getDevice(id)
isHardwareMouse(d) && d?.supportsSource(InputDevice.SOURCE_TOUCHPAD) != true
isHardwareMouse(d) && !isTouchpad(d)
}
private fun externalMouseAttached(): Boolean {
@@ -5603,7 +5655,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun updatePointerCapture() {
if (!::surfaceView.isInitialized) return
val view = window.decorView
val want = (pointerLocked || relativeMouseAttached()) && sessionOwnsInput() && hasWindowFocus() && mouseAttached()
val want = (pointerLocked || relativeMouseAttached()) && sessionOwnsInput() && hasWindowFocus() && pointerAttached()
releaseDesktopMouseGrab()
updateUsbMouse(want)
if (want == view.hasPointerCapture()) return
@@ -5656,7 +5708,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun dropMouseCursor() {
if (!mouseOwnsCursor || mouseAttached()) return
if (!mouseOwnsCursor || pointerAttached()) return
mouseOwnsCursor = false
uiHandler.removeCallbacks(cursorResync)
cursorVisible = false
@@ -5707,20 +5759,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun onCapturedPointer(event: MotionEvent): Boolean {
if (!event.isFromSource(InputDevice.SOURCE_MOUSE_RELATIVE)) return false
if (!com.droiddeck.launcher.input.PointerCapture.accepts(event)) return false
notePress(event)
val pad = com.droiddeck.launcher.input.PointerCapture.isTouchpad(event)
when (event.actionMasked) {
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {
if (pad && event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) capturedTouchpad.buttonPressed()
guestMouseButton(event.actionButton)?.let { heldButtons.set(8, it, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) }
}
else -> if (pad) return onCapturedTouchpad(event)
}
when (event.actionMasked) {
MotionEvent.ACTION_MOVE -> {
var dx = event.x
var dy = event.y
for (i in 0 until event.historySize) {
dx += event.getHistoricalX(i)
dy += event.getHistoricalY(i)
}
onRelativeMouse(dx, dy)
val delta = com.droiddeck.launcher.input.PointerCapture.delta(event)
onRelativeMouse(delta[0], delta[1])
}
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE ->
guestMouseButton(event.actionButton)?.let { heldButtons.set(8, it, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) }
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {}
MotionEvent.ACTION_SCROLL -> {
val v = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
if (v != 0f) sendSceneWheel(-Math.round(v))
@@ -5731,6 +5785,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
return true
}
private fun onCapturedTouchpad(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
val metrics = resources.displayMetrics
val scale = com.droiddeck.launcher.input.PointerCapture.touchpadScale(event, metrics.xdpi / 25.4f, metrics.widthPixels)
capturedPadMatrix.setScale(scale, scale)
capturedTouchpad.desktop = SessionState.mode == SessionService.MODE_DESKTOP
if (::touchpad.isInitialized) capturedTouchpad.sensitivity = touchpad.sensitivity
}
val scaled = MotionEvent.obtain(event)
scaled.transform(capturedPadMatrix)
val handled = capturedTouchpad.onTouch(scaled)
scaled.recycle()
return handled
}
private fun logInputDevice(what: String, deviceId: Int) {
val d = InputDevice.getDevice(deviceId) ?: return
if (!PadBridge.isFromController(d)) return
@@ -6127,8 +6196,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
drawerOpen = false
pcKeyboardOpen = false
achievementsOpen = false
pendingBackAction?.let(uiHandler::removeCallbacks)
pendingBackAction = null
backTaps.cancel()
releaseDrawerDirection()
onScreenControls?.releaseAll()
bottomInputControls?.releaseAll()
@@ -6291,6 +6359,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onScreenControls?.reload()
controllerSettings = ControllerPrefs.read(this)
resumed = true
boostGpuClock(panelOverGame)
updateKeyboardRoute()
retryFieldKeyboard(hasWindowFocus())
updateDesktopKeyboardButton()
@@ -6341,6 +6410,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (runtimeRemovalBlocked) return
physicalShortcuts.clear()
backQamInput.cancel()
backTaps.cancel()
mouseBackInput.cancel()
capturePausedFrame()
padBridge?.setInputEnabled(false)
@@ -6374,6 +6444,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (::scrollTouch.isInitialized) scrollTouch.cancel()
if (::padMouse.isInitialized) padMouse.reset()
resumed = false
boostGpuClock(false)
updateKeyboardRoute()
updatePointerCapture()
updatePadMotion()
@@ -6956,6 +7027,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
super.onWindowFocusChanged(hasFocus)
if (!hasFocus) com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this)
if (!hasFocus) backQamInput.cancel()
if (!hasFocus) backTaps.cancel()
if (!hasFocus) mouseBackInput.cancel()
if (!hasFocus && ::padMouse.isInitialized) padMouse.reset()
if (runtimeRemovalBlocked) return
@@ -7029,8 +7101,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (runtimeRemovalBlocked) { super.onDestroy(); return }
watching = false
releaseDrawerDirection()
pendingBackAction?.let(uiHandler::removeCallbacks)
pendingBackAction = null
backTaps.cancel()
if (::pip.isInitialized) pip.destroyed()
closeSecondScreen(reset = false)
glassesScope.cancel()
@@ -7162,6 +7233,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private const val PAD_SCROLL_POINTER_X = 0.985f
private const val PAD_SCROLL_HEIGHTS_PER_S = 3f
private const val AXIS_UNITS_PER_PIXEL = 3f
private const val CAPTURED_PAD_CENTRE = 1_000_000f
private const val KEY_LEFTCTRL = 29
private const val KEY_RIGHTCTRL = 97
private const val KEY_A = 30
@@ -16,7 +16,7 @@ object DeviceInfo {
val vk = VulkanInfo.query()
val gpu = GpuInfo.detect()
return listOf(
chip(), gpu(context, gpu), npu(context), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
chip(), gpu(context, gpu), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
).filter { it.rows.isNotEmpty() }
}
@@ -51,10 +51,6 @@ object DeviceInfo {
add("Family", read("/sys/devices/soc0/family"))
})
private fun npu(context: Context) = Section("NPU", NpuInfo.rows(
NpuInfo.detect(context.applicationInfo.nativeLibraryDir?.let(::File)),
))
private fun gpu(context: Context, gpu: GpuInfo) = Section("GPU", buildList<Pair<String, String>> {
add("GPU", gpu.name)
add("Family", gpu.family.label(gpu.name))
@@ -1,71 +0,0 @@
package com.droiddeck.launcher.gpu
import java.io.File
/** What this device's Qualcomm Hexagon NPU would offer a neural upscaler, and whether the app can reach it. */
object NpuInfo {
enum class Hexagon(val arch: String, val vtcmMb: Int) {
V68("v68", 4), V69("v69", 4), V73("v73", 4), V75("v75", 8), V79("v79", 8), V81("v81", 8),
}
enum class Access { OPEN, BROKERED, NO_NODE, DENIED }
data class Status(
val hexagon: Hexagon?,
val node: String?,
val access: Access,
val qnnRuntime: Boolean,
) {
val usable: Boolean get() = hexagon != null && (access == Access.OPEN || access == Access.BROKERED) && qnnRuntime
}
private val BY_MODEL = mapOf(
"SM8350" to Hexagon.V68, "SM8450" to Hexagon.V69, "SM8475" to Hexagon.V69,
"SM8550" to Hexagon.V73, "QCS8550" to Hexagon.V73, "SM8650" to Hexagon.V75,
"SM8750" to Hexagon.V79, "SM8850" to Hexagon.V81,
)
private val BY_PLATFORM = mapOf(
"lahaina" to Hexagon.V68, "taro" to Hexagon.V69, "cape" to Hexagon.V69, "kalama" to Hexagon.V73,
"pineapple" to Hexagon.V75, "sun" to Hexagon.V79, "canoe" to Hexagon.V81,
)
// The compute DSP is the one that runs HTP graphs; /dev/adsprpc-smd is the pre-5.x name of the same service.
internal val NODES = listOf("/dev/fastrpc-cdsp", "/dev/adsprpc-smd", "/dev/cdsprpc-smd")
// Qualcomm's dspservice hands an app a FastRPC fd over binder when the node itself is closed to apps.
internal const val DSP_SERVICE_MANIFEST = "/vendor/etc/vintf/manifest/vendor.qti.hardware.dsp-service.xml"
internal val QNN_LIBS = listOf("libQnnHtp.so", "libQnnSystem.so")
fun hexagon(
model: String = SocNames.model(),
platform: String = GpuInfo.systemProperty("ro.board.platform"),
): Hexagon? = BY_MODEL[SocNames.normalizedModel(model)] ?: BY_PLATFORM[platform.trim().lowercase()]
/** `canWrite` is access(2) for the app's own uid, so it answers for DAC but not SELinux. */
internal fun access(nodes: List<File>, broker: File = File(DSP_SERVICE_MANIFEST)): Pair<File?, Access> {
val present = nodes.firstOrNull { it.exists() } ?: return null to Access.NO_NODE
val access = when {
present.canRead() && present.canWrite() -> Access.OPEN
broker.exists() -> Access.BROKERED
else -> Access.DENIED
}
return present to access
}
fun detect(nativeLibDir: File?, hexagon: Hexagon? = hexagon()): Status {
val (node, access) = access(NODES.map(::File))
val qnn = nativeLibDir != null && QNN_LIBS.all { File(nativeLibDir, it).exists() }
return Status(hexagon, node?.path, access, qnn)
}
fun rows(status: Status): List<Pair<String, String>> = buildList {
add("Hexagon" to (status.hexagon?.let { "${it.arch} (${it.vtcmMb} MB VTCM)" } ?: "not recognised"))
add("FastRPC node" to when (status.access) {
Access.NO_NODE -> "none found"
Access.OPEN -> "${status.node} (app can open it)"
Access.BROKERED -> "${status.node} (closed to apps; the DSP service can hand over a descriptor)"
Access.DENIED -> "${status.node} (app cannot open it)"
})
add("QNN runtime" to if (status.qnnRuntime) "bundled" else "not bundled")
add("Neural upscaling" to if (status.usable) "possible" else "not available")
}
}
@@ -6,18 +6,15 @@ import android.os.Looper
class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap: (Boolean) -> Unit,
private val doubleTapMs: () -> Long = { 500 }, private val onCancel: () -> Unit = {},
private val holds: () -> Boolean = { true }) {
private val holds: () -> Boolean = { true }, atOnce: () -> Boolean = { false }, sameAction: () -> Boolean = { false }) {
private class Press(val hold: Runnable, var held: Boolean = false, var used: Boolean = false)
private val handler = Handler(Looper.getMainLooper())
private val presses = mutableMapOf<Int, Press>()
private val cancelled = mutableSetOf<Int>()
private var tapPending = false
private val singleTap = Runnable { tapPending = false; onTap(false) }
private val taps = BackTaps(doubleTapMs, atOnce, onTap, sameAction)
val awaitingTap: Boolean get() = taps.pending
private fun cancelTap() {
handler.removeCallbacks(singleTap)
tapPending = false
}
fun cancelTap() = taps.cancel()
fun onChordInput() {
if (presses.isEmpty()) return
@@ -46,7 +43,7 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
cancelled.remove(device)
if (!enabled || event.isCanceled) return false
if (device in presses) return true
handler.removeCallbacks(singleTap)
taps.hold()
val hold = Runnable {
val press = presses[device] ?: return@Runnable
if (!holds()) { press.used = true; cancelTap(); return@Runnable }
@@ -66,10 +63,8 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
if (press != null) {
handler.removeCallbacks(press.hold)
if (press.held && presses.values.none { it.held }) setPressed(false)
if (!press.used && !event.isCanceled) {
if (tapPending) { cancelTap(); onTap(true) }
else { tapPending = true; handler.postDelayed(singleTap, doubleTapMs()) }
} else if (event.isCanceled) cancelTap()
if (!press.used && !event.isCanceled) taps.tap()
else if (event.isCanceled) cancelTap()
}
press != null || wasCancelled || enabled
}
@@ -77,8 +72,8 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
}
}
fun cancel() {
cancelTap()
fun cancel(keepTap: Boolean = false) {
if (!keepTap) cancelTap()
val wasHeld = presses.values.any { it.held }
presses.values.forEach { handler.removeCallbacks(it.hold) }
cancelled.addAll(presses.keys)
@@ -0,0 +1,39 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
class BackTaps(
private val windowMs: () -> Long,
private val atOnce: () -> Boolean,
private val onTap: (Boolean) -> Unit,
private val sameAction: () -> Boolean = { false },
) {
private val handler = Handler(Looper.getMainLooper())
private var deferred = false
var pending = false
private set
private val expire = Runnable {
pending = false
if (deferred) onTap(false)
}
fun tap() {
if (pending) {
cancel()
if (deferred || !sameAction()) onTap(true)
return
}
pending = true
deferred = !atOnce()
handler.postDelayed(expire, windowMs())
if (!deferred) onTap(false)
}
fun hold() = handler.removeCallbacks(expire)
fun cancel() {
handler.removeCallbacks(expire)
pending = false
}
}
@@ -0,0 +1,33 @@
package com.droiddeck.launcher.input
import android.view.InputDevice
import android.view.MotionEvent
object PointerCapture {
fun accepts(event: MotionEvent): Boolean =
event.isFromSource(InputDevice.SOURCE_MOUSE_RELATIVE) ||
event.isFromSource(InputDevice.SOURCE_TOUCHPAD)
fun isTouchpad(event: MotionEvent): Boolean = event.isFromSource(InputDevice.SOURCE_TOUCHPAD)
fun delta(event: MotionEvent): FloatArray {
var dx = event.x
var dy = event.y
for (i in 0 until event.historySize) {
dx += event.getHistoricalX(i)
dy += event.getHistoricalY(i)
}
return floatArrayOf(dx, dy)
}
fun touchpadScale(unitsPerMm: Float, padWidth: Float, pixelsPerMm: Float, screenWidth: Int): Float = when {
unitsPerMm > 0f && pixelsPerMm > 0f -> pixelsPerMm / unitsPerMm
padWidth > 0f && screenWidth > 0 -> screenWidth / padWidth
else -> 1f
}
fun touchpadScale(event: MotionEvent, pixelsPerMm: Float, screenWidth: Int): Float {
val range = event.device?.getMotionRange(MotionEvent.AXIS_X, InputDevice.SOURCE_TOUCHPAD)
return touchpadScale(range?.resolution ?: 0f, range?.range ?: 0f, pixelsPerMm, screenWidth)
}
}
@@ -9,6 +9,7 @@ import kotlin.math.hypot
class TouchpadGestures(
private val slopPx: Float,
private val listener: PointerGestures.Listener,
private val holdDrags: Boolean = true,
) {
var x = 0f
private set
@@ -33,6 +34,7 @@ class TouchpadGestures(
private var held = false
private var secondDownAt = 0L
private var secondWasTap = false
private var pressed = false
private var twoFingers = false
private var scrollAnchorX = 0f
private var scrollAnchorY = 0f
@@ -90,6 +92,15 @@ class TouchpadGestures(
lastTapAt = 0L
}
fun buttonPressed() {
pressed = true
handler.removeCallbacks(longPress)
releaseClick()
travelled = slopPx + 1f
secondWasTap = false
lastTapAt = 0L
}
fun place(px: Float, py: Float) {
x = px.coerceIn(bounds.left, bounds.right)
y = py.coerceIn(bounds.top, bounds.bottom)
@@ -115,7 +126,7 @@ class TouchpadGestures(
releaseClick()
lastX = event.x; lastY = event.y
downAt = event.eventTime
travelled = 0f; held = false; twoFingers = false; scrolled = false; secondWasTap = false
travelled = 0f; held = false; twoFingers = false; scrolled = false; secondWasTap = false; pressed = false
fingers = 1; pinching = false
anchorId = event.getPointerId(0); moverId = -1; holdDrag = false; scrollLocked = false
if (clicks && event.eventTime - lastTapAt < TouchTiming.DOUBLE_TAP_MS) {
@@ -123,7 +134,7 @@ class TouchpadGestures(
press(PointerGestures.BTN_LEFT)
} else {
dragging = false
if (clicks) handler.postDelayed(longPress, TouchTiming.HOLD_MS)
if (clicks && holdDrags) handler.postDelayed(longPress, TouchTiming.HOLD_MS)
}
return true
}
@@ -142,7 +153,7 @@ class TouchpadGestures(
if (holdDrag) return true
twoFingers = true
secondDownAt = event.eventTime
secondWasTap = true
secondWasTap = !pressed
scrollAnchorX = (event.getX(0) + event.getX(1)) / 2f
scrollAnchorY = (event.getY(0) + event.getY(1)) / 2f
pinchSpan = span(event)
@@ -153,7 +164,7 @@ class TouchpadGestures(
val mi = if (moverId == -1) -1 else event.findPointerIndex(moverId)
if (ai >= 0 && mi >= 0) {
val mx = event.getX(mi); val my = event.getY(mi)
if (!holdDrag && !scrolled && !scrollLocked) {
if (holdDrags && !holdDrag && !scrolled && !scrollLocked) {
val anchorMoved = abs(event.getX(ai) - anchorStartX) + abs(event.getY(ai) - anchorStartY)
val moverMoved = abs(mx - moverStartX) + abs(my - moverStartY)
if (anchorMoved >= slopPx) {
@@ -18,10 +18,24 @@ object GpuClockPin {
var failed = false
private set
val supported: Boolean by lazy { File(KGSL_NODE).exists() }
var supported: Boolean = File(KGSL_NODE).exists()
internal set
internal var turbo: (Boolean) -> Unit = { WaylandCompositor.nativeSetGpuTurbo(it) }
private var live = false
@Volatile
private var boosted = false
private fun wanted(context: Context) = boosted || SessionPrefs.gpuClockPin(context)
fun boost(on: Boolean): Boolean {
if (boosted == on) return false
boosted = on
return true
}
@Synchronized
fun start(context: Context): String {
live = true
@@ -30,11 +44,11 @@ object GpuClockPin {
private fun hold(context: Context): String {
failed = false
if (!SessionPrefs.gpuClockPin(context)) return "gpu clock: governed"
if (!wanted(context)) return "gpu clock: governed"
if (!supported) return "gpu clock: no $KGSL_NODE, left governed"
return try {
File(context.filesDir, MARKER).createNewFile()
WaylandCompositor.nativeSetGpuTurbo(true)
turbo(true)
pinned = true
"gpu clock: held at its top"
} catch (t: Throwable) {
@@ -48,13 +62,14 @@ object GpuClockPin {
@Synchronized
fun sync(context: Context): String? {
if (!live) return null
if (!SessionPrefs.gpuClockPin(context) && pinned) clear(context)
if (!wanted(context) && pinned) clear(context)
return hold(context)
}
@Synchronized
fun stop(context: Context) {
live = false
boosted = false
if (pinned) clear(context)
}
@@ -66,7 +81,7 @@ object GpuClockPin {
private fun clear(context: Context) {
if (supported) {
try {
WaylandCompositor.nativeSetGpuTurbo(false)
turbo(false)
} catch (t: Throwable) {
Log.w(TAG, "clear", t)
}
@@ -1,49 +0,0 @@
package com.droiddeck.launcher.gpu
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class NpuInfoTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun modelPicksTheHexagonGenerationAndFallsBackToThePlatform() {
assertEquals(NpuInfo.Hexagon.V79, NpuInfo.hexagon("SM8750", "sun"))
assertEquals(NpuInfo.Hexagon.V81, NpuInfo.hexagon("QTI SM8850", ""))
assertEquals(NpuInfo.Hexagon.V73, NpuInfo.hexagon("", "Kalama"))
assertNull(NpuInfo.hexagon("MT6989", "mt6989"))
}
@Test fun nodeAccessSeparatesMissingFromDenied() {
assertEquals(NpuInfo.Access.NO_NODE, NpuInfo.access(listOf(File(tmp.root, "nope"))).second)
val node = tmp.newFile("fastrpc-cdsp")
assertEquals(NpuInfo.Access.OPEN, NpuInfo.access(listOf(File(tmp.root, "nope"), node)).second)
node.setWritable(false)
val absent = File(tmp.root, "no-broker")
if (!node.canWrite()) {
assertEquals(NpuInfo.Access.DENIED, NpuInfo.access(listOf(node), absent).second)
assertEquals(NpuInfo.Access.BROKERED, NpuInfo.access(listOf(node), tmp.newFile("dsp-service.xml")).second)
}
}
@Test fun usableNeedsChipNodeAndRuntime() {
val ok = NpuInfo.Status(NpuInfo.Hexagon.V79, "/dev/fastrpc-cdsp", NpuInfo.Access.OPEN, true)
assertTrue(ok.usable)
assertTrue(ok.copy(access = NpuInfo.Access.BROKERED).usable)
assertFalse(ok.copy(access = NpuInfo.Access.DENIED).usable)
assertFalse(ok.copy(qnnRuntime = false).usable)
assertFalse(ok.copy(hexagon = null).usable)
}
@Test fun runtimeIsBundledOnlyWhenEveryLibraryIsPresent() {
NpuInfo.QNN_LIBS.dropLast(1).forEach { File(tmp.root, it).createNewFile() }
assertFalse(NpuInfo.detect(tmp.root, NpuInfo.Hexagon.V79).qnnRuntime)
File(tmp.root, NpuInfo.QNN_LIBS.last()).createNewFile()
assertTrue(NpuInfo.detect(tmp.root, NpuInfo.Hexagon.V79).qnnRuntime)
}
}
@@ -63,6 +63,46 @@ class BackQamInputTest {
}
}
@Test fun anAtOnceSingleTapActsOnReleaseAndADoubleTapStillFollows() {
val direct = BackQamInput(changes::add, taps::add, atOnce = { true })
fun press(action: Int) = direct.onKeyEvent(KeyEvent(action, KeyEvent.KEYCODE_BACK), true)
press(KeyEvent.ACTION_DOWN)
assertTrue(taps.isEmpty())
press(KeyEvent.ACTION_UP)
assertEquals(listOf(false), taps)
assertTrue(direct.awaitingTap)
advance(300)
press(KeyEvent.ACTION_DOWN)
advance(400)
assertTrue(direct.awaitingTap)
press(KeyEvent.ACTION_UP)
assertEquals(listOf(false, true), taps)
assertFalse(direct.awaitingTap)
assertTrue(changes.isEmpty())
}
@Test fun cancellingOnlyTheTapKeepsAPressThatIsAlreadyDown() {
val direct = BackQamInput(changes::add, taps::add, atOnce = { true })
fun press(action: Int) = direct.onKeyEvent(KeyEvent(action, KeyEvent.KEYCODE_BACK), true)
press(KeyEvent.ACTION_DOWN)
press(KeyEvent.ACTION_UP)
advance(100)
press(KeyEvent.ACTION_DOWN)
direct.cancelTap()
assertFalse(direct.awaitingTap)
press(KeyEvent.ACTION_UP)
assertEquals(listOf(false, false), taps)
}
@Test fun anAtOnceTapStopsAwaitingWhenTheWindowEnds() {
val direct = BackQamInput(changes::add, taps::add, atOnce = { true })
direct.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK), true)
direct.onKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK), true)
advance(500)
assertFalse(direct.awaitingTap)
assertEquals(listOf(false), taps)
}
@Test fun aHoldStartsAt700msAndNeverProducesATap() {
assertTrue(send(KeyEvent.ACTION_DOWN))
advance(699)
@@ -191,6 +231,19 @@ class BackQamInputTest {
assertTrue(taps.isEmpty())
}
@Test fun cancellingHeldInputCanKeepThePendingTapForTheDoubleAction() {
val direct = BackQamInput(changes::add, taps::add, atOnce = { true })
fun press(action: Int) = direct.onKeyEvent(KeyEvent(action, KeyEvent.KEYCODE_BACK), true)
press(KeyEvent.ACTION_DOWN)
press(KeyEvent.ACTION_UP)
direct.cancel(keepTap = true)
assertTrue(direct.awaitingTap)
press(KeyEvent.ACTION_DOWN)
press(KeyEvent.ACTION_UP)
assertEquals(listOf(false, true), taps)
assertFalse(direct.awaitingTap)
}
@Test fun cancellationAlsoDiscardsAPendingSingleTap() {
send(KeyEvent.ACTION_DOWN)
send(KeyEvent.ACTION_UP)
@@ -0,0 +1,133 @@
package com.droiddeck.launcher.input
import android.os.Looper
import java.time.Duration
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE)
class BackTapsTest {
private val seen = mutableListOf<Boolean>()
private var atOnce = true
private var window = 500L
private val taps = BackTaps({ window }, { atOnce }, seen::add)
@Test fun aSingleTapActsWithoutWaitingForTheWindow() {
taps.tap()
assertEquals(listOf(false), seen)
assertTrue(taps.pending)
advance(500)
assertEquals(listOf(false), seen)
assertFalse(taps.pending)
}
@Test fun aSecondTapInsideTheWindowAddsTheDoubleAction() {
taps.tap()
advance(499)
taps.tap()
assertEquals(listOf(false, true), seen)
assertFalse(taps.pending)
advance(1000)
assertEquals(listOf(false, true), seen)
}
@Test fun aTapAfterTheWindowIsANewSingleTap() {
taps.tap()
advance(500)
taps.tap()
assertEquals(listOf(false, false), seen)
}
@Test fun aDeferredSingleTapWaitsForTheWindow() {
atOnce = false
taps.tap()
advance(499)
assertTrue(seen.isEmpty())
advance(1)
assertEquals(listOf(false), seen)
}
@Test fun aDeferredDoubleTapProducesOnlyTheDoubleAction() {
atOnce = false
taps.tap()
advance(100)
taps.tap()
advance(1000)
assertEquals(listOf(true), seen)
}
@Test fun theConfiguredWindowAppliesInBothModes() {
for (mode in listOf(true, false)) for (ms in listOf(100L, 800L)) {
seen.clear()
atOnce = mode
window = ms
taps.tap()
advance(ms - 1)
taps.tap()
assertEquals(true, seen.last())
advance(ms)
assertFalse(taps.pending)
}
}
@Test fun holdKeepsTheWindowOpenUntilTheNextTap() {
taps.tap()
advance(400)
taps.hold()
advance(5000)
assertTrue(taps.pending)
taps.tap()
assertEquals(listOf(false, true), seen)
}
@Test fun cancelDropsADeferredTapAndClosesTheWindow() {
atOnce = false
taps.tap()
taps.cancel()
advance(1000)
assertTrue(seen.isEmpty())
assertFalse(taps.pending)
taps.tap()
advance(500)
assertEquals(listOf(false), seen)
}
@Test fun aDoubleTapWhoseActionMatchesTheImmediateSingleTapIsNotRepeated() {
var same = true
val coalesced = BackTaps({ window }, { atOnce }, seen::add, { same })
coalesced.tap()
coalesced.tap()
assertEquals(listOf(false), seen)
assertFalse(coalesced.pending)
same = false
coalesced.tap()
coalesced.tap()
assertEquals(listOf(false, false, true), seen)
}
@Test fun aDeferredDoubleTapStillActsWhenBothActionsMatch() {
atOnce = false
val coalesced = BackTaps({ window }, { atOnce }, seen::add, { true })
coalesced.tap()
coalesced.tap()
advance(1000)
assertEquals(listOf(true), seen)
}
@Test fun aHeldTapCancelledBeforeItsReleaseLeavesTheNextTapASingleTap() {
val coalesced = BackTaps({ window }, { atOnce }, seen::add, { true })
coalesced.tap()
coalesced.hold()
coalesced.cancel()
advance(5000)
coalesced.tap()
assertEquals(listOf(false, false), seen)
}
private fun advance(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms))
}
@@ -0,0 +1,77 @@
package com.droiddeck.launcher.input
import android.view.InputDevice
import android.view.MotionEvent
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE)
class PointerCaptureTest {
@Test fun aCapturedMouseReportsItsPositionAsMovement() {
val event = event(MotionEvent.ACTION_MOVE, InputDevice.SOURCE_MOUSE_RELATIVE, x = 12f, y = -7f)
try {
assertTrue(PointerCapture.accepts(event))
assertFalse(PointerCapture.isTouchpad(event))
assertArrayEquals(floatArrayOf(12f, -7f), PointerCapture.delta(event), 0.001f)
} finally {
event.recycle()
}
}
@Test fun batchedMouseSamplesAddUp() {
val event = event(MotionEvent.ACTION_MOVE, InputDevice.SOURCE_MOUSE_RELATIVE, x = 3f, y = -5f)
try {
event.addBatch(1L, arrayOf(MotionEvent.PointerCoords().apply { x = 2f; y = 4f }), 0)
assertArrayEquals(floatArrayOf(5f, -1f), PointerCapture.delta(event), 0.001f)
} finally {
event.recycle()
}
}
@Test fun aCapturedTouchpadIsACapturedPointer() {
val event = event(MotionEvent.ACTION_DOWN, InputDevice.SOURCE_TOUCHPAD, x = 800f, y = 400f)
try {
assertTrue(PointerCapture.accepts(event))
assertTrue(PointerCapture.isTouchpad(event))
} finally {
event.recycle()
}
}
@Test fun anUncapturedMouseIsNotACapturedPointer() {
val event = event(MotionEvent.ACTION_HOVER_MOVE, InputDevice.SOURCE_MOUSE, x = 12f, y = -7f)
try {
assertFalse(PointerCapture.accepts(event))
} finally {
event.recycle()
}
}
@Test fun touchpadTravelMatchesTheSameDistanceOnScreen() {
assertEquals(0.5f, PointerCapture.touchpadScale(unitsPerMm = 20f, padWidth = 2000f, pixelsPerMm = 10f, screenWidth = 1920), 0.001f)
}
@Test fun aTouchpadWithoutAResolutionSpansTheScreen() {
assertEquals(1.92f, PointerCapture.touchpadScale(unitsPerMm = 0f, padWidth = 1000f, pixelsPerMm = 10f, screenWidth = 1920), 0.001f)
}
@Test fun aTouchpadWithoutARangeKeepsItsUnits() {
assertEquals(1f, PointerCapture.touchpadScale(unitsPerMm = 0f, padWidth = 0f, pixelsPerMm = 10f, screenWidth = 1920), 0.001f)
}
private fun event(action: Int, source: Int, x: Float, y: Float): MotionEvent {
val properties = arrayOf(MotionEvent.PointerProperties().apply {
id = 0
toolType = MotionEvent.TOOL_TYPE_FINGER
})
val coords = arrayOf(MotionEvent.PointerCoords().apply { this.x = x; this.y = y })
return MotionEvent.obtain(0L, 0L, action, 1, properties, coords, 0, 0, 1f, 1f, 0, 0, source, 0)
}
}
@@ -331,6 +331,81 @@ class TouchpadGesturesTest {
assertEquals(listOf("left down", "left up", "left down"), events)
}
@Test fun aRestingFingerNeverDragsWhenHoldDragsAreOff() {
touchpad = TouchpadGestures(SLOP, listener, holdDrags = false)
touchpad.bounds = RectF(0f, 0f, 1920f, 1080f)
touchpad.place(960f, 540f)
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
advance(TouchTiming.HOLD_MS + 100)
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 300f))
advance(10)
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 300f), 2 to (620f to 300f))
advance(10)
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 300f), 2 to (640f to 300f))
assertFalse(events.any { it.startsWith("left") || it == "long press" })
}
@Test fun tapsStillClickWhenHoldDragsAreOff() {
touchpad = TouchpadGestures(SLOP, listener, holdDrags = false)
tap()
assertEquals(listOf("left down"), events)
}
@Test fun aPhysicalButtonPressIsNotAlsoATap() {
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
touchpad.buttonPressed()
advance(80)
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f))
advance(TouchTiming.HOLD_MS + 100)
assertTrue(events.isEmpty())
}
@Test fun aPhysicalButtonPressDuringTwoFingersIsNotARightClick() {
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 300f))
touchpad.buttonPressed()
advance(40)
touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 300f), 2 to (600f to 300f))
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f))
assertTrue(events.isEmpty())
}
@Test fun aSecondFingerAfterAPhysicalButtonPressIsNotARightClick() {
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
touchpad.buttonPressed()
advance(10)
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 300f))
advance(40)
touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 300f), 2 to (600f to 300f))
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f))
advance(TouchTiming.HOLD_MS + 100)
assertTrue(events.isEmpty())
twoFingerTapStillRightClicks()
}
@Test fun aPhysicalButtonPressReleasesAPendingTapClickFirst() {
tap()
assertEquals(listOf("left down"), events)
touchpad.buttonPressed()
assertEquals(listOf("left down", "left up"), events)
advance(TouchTiming.CLICK_MS + 100)
assertEquals(listOf("left down", "left up"), events)
}
private fun twoFingerTapStillRightClicks() {
advance(1000)
events.clear()
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 300f))
advance(40)
touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 300f), 2 to (600f to 300f))
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f))
advance(TouchTiming.HOLD_MS + 100)
assertTrue("right down" in events)
}
private fun tap() {
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
advance(80)
@@ -2,7 +2,9 @@ package com.droiddeck.launcher.session
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@@ -14,7 +16,21 @@ import org.robolectric.annotation.Config
class GpuClockPinTest {
private val context = RuntimeEnvironment.getApplication()
@After fun stop() { GpuClockPin.stop(context) }
private val calls = mutableListOf<Boolean>()
private val node = GpuClockPin.supported
private val turbo = GpuClockPin.turbo
@After fun stop() {
GpuClockPin.stop(context)
GpuClockPin.supported = node
GpuClockPin.turbo = turbo
SessionPrefs.setGpuClockPin(context, false)
}
private fun fakeGpu() {
GpuClockPin.supported = true
GpuClockPin.turbo = { calls += it }
}
@Test fun aToggleOutsideASessionSaysNothing() {
SessionPrefs.setGpuClockPin(context, true)
@@ -31,4 +47,52 @@ class GpuClockPinTest {
SessionPrefs.setGpuClockPin(context, false)
assertEquals(started, GpuClockPin.sync(context))
}
@Test fun aBoostHoldsTheClockOnlyWhileItLasts() {
fakeGpu()
assertEquals("gpu clock: governed", GpuClockPin.start(context))
assertTrue(GpuClockPin.boost(true))
assertEquals("gpu clock: held at its top", GpuClockPin.sync(context))
assertFalse(GpuClockPin.boost(true))
assertTrue(GpuClockPin.boost(false))
assertEquals("gpu clock: governed", GpuClockPin.sync(context))
assertEquals(listOf(true, false), calls)
}
@Test fun endingABoostKeepsTheHoldTheUserTurnedOn() {
fakeGpu()
SessionPrefs.setGpuClockPin(context, true)
GpuClockPin.start(context)
GpuClockPin.boost(true)
GpuClockPin.sync(context)
GpuClockPin.boost(false)
assertEquals("gpu clock: held at its top", GpuClockPin.sync(context))
assertFalse(false in calls)
}
@Test fun aBoostOutsideASessionDoesNothing() {
fakeGpu()
GpuClockPin.boost(true)
assertNull(GpuClockPin.sync(context))
assertTrue(calls.isEmpty())
}
@Test fun aBoostDoesNotOutliveItsSession() {
fakeGpu()
GpuClockPin.start(context)
GpuClockPin.boost(true)
GpuClockPin.sync(context)
GpuClockPin.stop(context)
assertEquals("gpu clock: governed", GpuClockPin.start(context))
assertEquals(listOf(true, false), calls)
}
@Test fun aBoostWithoutTheGpuNodeLeavesTheClockGoverned() {
GpuClockPin.supported = false
GpuClockPin.turbo = { calls += it }
GpuClockPin.start(context)
GpuClockPin.boost(true)
assertEquals("gpu clock: no /dev/kgsl-3d0, left governed", GpuClockPin.sync(context))
assertTrue(calls.isEmpty())
}
}
-129
View File
@@ -1,129 +0,0 @@
# Neural upscaling on the Hexagon NPU
Reference: [Winlator-NeuralScale](https://github.com/michaelisomer-cyber/Winlator-NeuralScale), a Winlator fork that
runs AMD FSR 4 on the Qualcomm Hexagon HTP through QNN, with GPU (DP4a) FSR 4 / XeSS / FSR 3.1 fallbacks. This note
records what carries over to DroidDeck, what does not, and what has been built so far.
## How the reference works
A Vulkan layer in the game's process intercepts the game's own upscaler calls (FSR 2/3/4, DLSS through an NGX
bridge, XeSS) via replacement DLLs. Those calls hand over colour, depth, motion vectors, exposure and jitter. The
layer runs the FSR 4 network (INT8, compiled on the device by `libQnnHtpPrepare.so`) on the NPU, with Vulkan passes
before and after it and `AHardwareBuffer` for the hand-off.
## What carries over, what does not
| Piece | In DroidDeck |
|---|---|
| Game-side hook (DLL replacement, NGX/FFX bridges) | The guest runs Steam under FEX and Proton, so the same Windows-side bridge DLLs could apply, but nothing in the repo loads them yet. |
| Temporal inputs (depth, motion vectors, jitter) | Only exist inside the guest. The Wayland compositor (`waylandcomp`, where FSR 1 / SGSR / frame generation run) sees a finished colour frame, so FSR 4 cannot run there. A compositor-side network would have to be a spatial-only super-resolution model, a different thing from FSR 4. |
| QNN runtime and skel libraries | Qualcomm's, not redistributable here. They would come from the user's own QAIRT SDK or a runtime download. |
| FSR 4 weights | AMD's. The reference ships them in its APK; DroidDeck should not copy them without a licence check. |
| DP4a GPU path | Independent of the NPU and the most portable part. Needs the same guest-side hook. |
## Findings: the NPU is reachable from an unprivileged app
Tested on the Retroid Pocket Duo (SM8750, Hexagon v79) and the AYANEO Pocket FIT Elite (SM8750P, stock, no root).
**The node is closed, but there is a supported way around it.**
- `/dev/fastrpc-cdsp` is `0664 system:system` and the two `-secure` nodes are `0644`. A real app uid (checked with
`run-as` as uid 10185) fails `access(W_OK)`. This is Qualcomm's own `ueventd` setting, not an OEM quirk.
- Qualcomm's `libcdsprpc.so` is not loadable by an app on this firmware: `libcdsprpc.so` and even `libOpenCL.so` fail
with "not found" from an app namespace, with or without `<uses-native-library>`, and a copy would need private
system libraries (`libutils`, `libhidlbase`, `libcutils`). So QNN stubs that `dlopen("libcdsprpc.so")` fail today.
- The vendor AIDL service `vendor.qti.hardware.dsp.IDspService/default` (process `dspservice`, uid `system`) opens
the node on behalf of callers. From the app, `AServiceManager_checkService` returns it,
`getNewDSPSession(int)` returns an `IDspManager`, and `openSession(DSPDomain)` returns a `FastrpcDev` whose
`NativeHandle` carries an open descriptor for `/dev/fastrpc-cdsp`. `readlink` on it gives `/dev/fastrpc-cdsp`.
- On that descriptor, from the app: `FASTRPC_IOCTL_GET_DSP_INFO` (`_IOWR('R', 13, ...)`) succeeds and reports
unsigned-PD support (attribute 1 = 1). `FASTRPC_IOCTL_INIT_ATTACH` returns `EACCES`, and the kernel logs "untrusted
app trying to attach to privileged DSP PD". That is the expected outcome: an app must create an unsigned PD
(`INIT_CREATE`) instead of attaching to the root PD.
Wire format that worked (transaction codes are the AIDL order): `IDspService` 1 = `getNewDSPSession(int)`;
`IDspManager` 2 = `openSession`. The `in DSPDomain` argument is written as `[1 (non-null)][size][domain]`; domain 3 is
the compute DSP. The reply is `[status][1][size][int][int][NativeHandle: size, fd count, fds, int count]`.
`tools/experiments/npu-fastrpc-probe` reproduces all of it; results go to logcat tag `NPUPROBE`.
### AYN Thor (QCS8550, Hexagon v73, Android 13, release-keys): closed
- `/dev/adsprpc-smd` is `0664 system:system` and `open(O_RDWR)` from an app gives `EACCES`. There is no
`/dev/fastrpc-cdsp`.
- There is no `IDspService` here. `checkService` returns null, and SELinux logs a `find` denial for
`untrusted_app` on `default_android_service`.
- `dlopen("libcdsprpc.so")` fails with "not found" even with `<uses-native-library>` declared.
- So no route was found on this device without root. SELinux is enforcing here, which is the case the 8 Elite tests
could not cover.
### How BananaNative's PR (moceure/BananaNative #703) gets in
It declares `<uses-native-library android:name="libcdsprpc.so" android:required="false"/>`, then
`dlopen("libcdsprpc.so")`, `remote_handle_control(4, {domain 3, enable 1})` to request an unsigned PD, and an
`ADSP_LIBRARY_PATH` that puts the app's own `adsp` directory first so the DSP can load the HTP skel from the app.
That only works on firmware that exposes the vendor library to apps; its logs are from a Xiaomi phone on a v81 SoC.
It does not work on the three Qualcomm-reference style builds tried here (Duo, FIT Elite, Thor), where the library is
invisible to app namespaces. Useful from it, if the NPU path goes ahead: a process-wide ref-counted QNN HTP runtime
shared by two users, zero-copy `AHardwareBuffer` DMA-BUF registration, a thermal power tier (turbo, balanced, low)
with hysteresis, and clamping the ADPF target duration to the frame-generated output period so the PowerHAL does not
halve a 2x frame-generated game. Its MIT-licensed GLSL for flow, splat and blend is a possible reference for DD-FG.
Its QNN graph binaries come from a companion repo; where they derive from is a licence question.
Caveats:
- SELinux is permissive on both devices (dev-keys builds). On an enforcing production build, `untrusted_app` may not
be allowed to find `IDspService`, and that has not been tried.
- Nothing has run on the NPU yet. A descriptor and a capability query are not a graph execution.
- The reference fork does not need any of this on devices where the node is world-writable.
## vk-fsr4 (han39835/vk-fsr4, GPL-3.0): FSR 4 INT8 on the GPU, no NPU
An implicit Vulkan layer plus a drop-in replacement for AMD's `amd_fidelityfx_upscaler_vk` provider. It runs FSR 4.1.2
as INT8 compute shaders on any Vulkan GPU with `shaderInt8` and `shaderIntegerDotProduct` (DP4a), and keeps the
cooperative-matrix FP8 path for RDNA 3/4. Aimed at AMD and Linux, but nothing in the INT8 path is vendor specific.
- **Assets:** 31 MB of precompiled SPIR-V for INT8 (1080, 2160 and 4320 tiers, each in `native` and `ultraperf`) plus
quantised weights. The DXIL from AMD's DLL was converted to SPIR-V at build time with `dxil-spirv`, which is not
linked into the provider. The tools to repeat that are in the repo (`tools/extract`, `tools/convert`).
- **Two entry points.** As an FFX provider, games that already call FSR 3/4 through the FFX API get FSR 4 with the
game's own motion vectors, depth and jitter: the exact inputs, and the most robust option. As a layer without the
API (`F4_MV=1`), it guesses which descriptor holds the motion vectors by fingerprinting Unreal TSR layouts. The
author says other engines "may or may not match", so only the provider mode is worth building on.
- **Licence, checked:** the author's claim that the 4.1.2 DLL is MIT licensed holds up. AMD's FidelityFX SDK 2.4.0
`license.md` starts with a restrictive default (binary-only redistribution, no reverse engineering) "except as noted
below". It then lists the files "subject to" an MIT licence, and that list includes
`signedbin/amd_fidelityfx_upscaler_dx12.dll` and `amd_fidelityfx_upscaler_vk.dll`. So the 4.1.x shaders and weights
are redistributable with the MIT notice, which removes the AMD half of the earlier licence concern for that version.
Which SDK version a given weights file came from still has to be pinned (the repo pins 4.1.2.4555 by SHA-256).
Qualcomm's QNN libraries are a separate matter. This is a reading of the licence file, not legal advice.
- **Frame generation:** FSR 4.0.2 ML frame generation is bundled but needs RDNA 4 WMMA, so it is not usable here.
- **Fit with DroidDeck:** GPL-3.0, same as DroidDeck. The provider route would sit in the guest, in front of
vkd3d-proton, where the game's FFX calls arrive. It needs no NPU access, so it works on the Thor.
- **Risk to check first:** the INT8 plan marks most passes `require_wave32`. Adreno runs 64 or 128 wide waves, so
either the passes can run at those widths or they need the variants the Winlator fork's Adreno path uses
(`dvj5411/fsr4vk`). Also unmeasured: INT8 FSR 4 on a handheld GPU may cost more than it saves at 1080p to 4K.
## Built so far
- `gpu/NpuInfo.kt`: maps the SoC model or board platform to a Hexagon generation (v68 to v81, with the VTCM size the
reference caps `vtcmSizeInMB` to), checks whether the app's uid can open the FastRPC node (or the DSP service that
can hand it over), and whether the QNN libraries are bundled. Shown as an "NPU" section in Device info.
- `NpuInfoTest`.
## Next steps, in order
1. Create an unsigned PD on the brokered descriptor (`INIT_CREATE`, with the DSP-side `fastrpc_shell_unsigned_3`) and
invoke one remote call. Qualcomm's open-source userspace library (`quic/fastrpc`, BSD-3) implements this; it would
be built as the app's own `libcdsprpc.so`, with the device open replaced by the binder call above. QNN stubs
resolve `libcdsprpc.so` from the app's library directory, so they would pick it up unchanged.
2. Run a QNN HTP graph with the user's own QAIRT libraries (v79 skel for the 8 Elite) to prove an end-to-end NPU run.
3. Check the binder route on an enforcing 8 Elite build and on an 8 Elite Gen 5 device. Thor (v73) has no route at all.
4. Decide the hook point. Guest-side (Winlator's approach) is the only one that can run FSR 4; compositor-side
limits it to spatial super-resolution.
5. GPU-only FSR 4.1.2 INT8 (DP4a) as an FFX provider in the guest (see vk-fsr4), since it needs no NPU access and
exercises the same plumbing. First measure: wave size on Adreno, and cost per frame on the Thor.
6. Per-architecture QNN cache directories (`v73/`, `v75/`, `v79/`, `v81/`) and a fallback to the GPU path whenever
`NpuInfo.usable` is false.
7. Pin the exact AMD SDK version for any weights that ship (4.1.2.4555 is MIT per the SDK 2.4.0 licence file), keep
the MIT notice with them, and review Qualcomm's QNN licence separately before anything of theirs is bundled or
downloaded.
+5 -4
View File
@@ -35,10 +35,11 @@ GAMESCOPE_COMMIT=8f212644c46460549035971ab914421180f61a7c
GAMESCOPE_PATCHES="0117-wsi-cache-present-bypass-check.patch 0119-wsi-default-images-under-limiter.patch"
VULKAN_HEADERS_TAG=v1.4.341
# The bionic DroidDeck-Proton layer the pack is made for: linked against (libwayland-client) and checked against, not packed.
# Layer v16 (067c719d) plus the ARM64EC code-map fix for 39-bit hosts (d4c9ffa7, run 44291095238).
LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261118-v16-unwind/DroidDeck-Proton-11.0-12.8-arm64ec.wcp
LAYER_SHA256=3cc74b877bc8707d75aa2cc22e335373b6a6c0b6b1937c7b3c2cd98e55de2e89 # proton-wine d48e30a1 (a188791d + fecf7376 on d4c9ffa7)
LAYER_VERSION=12.8
# Layer v18: DroidDeck-Proton 11-14.1 (Valve Wine a47c73f52fd7, as GE-Proton11-14), the build Bannerlator ships; it
# carries the ARM64EC code-map and unwind fixes the 12.8 layer had (5ebfaa6f, 2515a989, e88fab40).
LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261124-v18/DroidDeck-proton-11.0-14.1-arm64ec.wcp
LAYER_SHA256=bf94176180e96584185835f9e80b168666f9fa752aa9583cfedb8fe493134ff6 # proton-wine 1a5735e7 (run 45926928349)
LAYER_VERSION=14.1
# Packed into the DroidDeck-Bionic tool next to the layer: FEX with Android-built unix libraries, and default
# DXVK / VKD3D-Proton (DroidDeck components can swap these in files/lib/wine/{dxvk,vkd3d-proton} later).
FEX_URL=https://github.com/The412Banner/Nightlies/releases/download/FEXCore-2611.1/FEXCore-2611.1-unix.wcp
+1
View File
@@ -1,6 +1,7 @@
# GStreamer plugins packed for winegstreamer (game video/audio), from the imagefs's lib/gstreamer-1.0 by name
# (libgst<name>.so): Proton's usual set as far as this imagefs has it (no vpx; videoconvert+videoscale are videoconvertscale).
coreelements
debug
app
audioconvert
audiorate
+18
View File
@@ -109,6 +109,9 @@ export NTSYNC_SHM=$COMPAT/ntsync-shm
# DroidDeck's Force SSBS (its glibc libssbs.so preload) is bionic Wine's own WINE_FORCE_SSBS
on "${DROIDDECK_FORCE_SSBS:-}" && export WINE_FORCE_SSBS=1
export HODLL=libwow64fex.dll WINEDEBUG=err+all,fixme-all
# The network adapter list (GetAdaptersAddresses) from the layer's getifaddrs code: its default if_nameindex code never
# answered here, and the Paradox Launcher (Europa Universalis IV) waited on it forever.
export WINE_NEW_NDIS=${WINE_NEW_NDIS:-1}
export XENVIRONMENT=$TOOL/bionic/Xdefaults
# The adapter's Wayland swapchain gets its buffers back from gamescope later than DroidDeck-Proton's Turnip does;
# with gamescope's default three images the game waits for one about a fifth of the time at high frame rates.
@@ -306,6 +309,21 @@ if [ "$verb" != runinprefix ] && prefix_busy; then
fi
prefix_busy || rm -f "$NTSYNC_SHM".v*
# Steam's running client, as a game's steam_api checks it: Proton names its steam.exe (the prefix's first program,
# alive while the game runs), which this tool does not start. Here the first program is the one Steam started, so a
# launcher that starts the game and quits (EU4's dowser.exe) left a game that reported "Steam not detected". The
# PID is the one this tool's own prefixes carry.
steam_pid() {
R=$COMPAT/pfx/user.reg
[ -f "$R" ] || return 0
awk '/^\[/ { on = index($0, "[Software\\\\Valve\\\\Steam\\\\ActiveProcess]") == 1 }
on && /^"PID"=dword:/ && $0 != "\"PID\"=dword:0000fffe" { found = 1 } END { exit !found }' "$R" || return 0
awk '/^\[/ { on = index($0, "[Software\\\\Valve\\\\Steam\\\\ActiveProcess]") == 1 }
on && /^"PID"=dword:/ { print "\"PID\"=dword:0000fffe"; next } { print }' "$R" > "$R.dd-new.$$" && mv -f "$R.dd-new.$$" "$R" &&
echo "$(date +%H:%M:%S) Steam's process ID in the registry set to this tool's"
}
prefix_busy || steam_pid
# Links into a tool that is gone (an older DroidDeck-Bionic, a deleted DroidDeck-Proton) or to a file it no longer has.
# Wine's update cannot write over them, so drivers (network, controller) and other files stay missing. Drop them and
# clear both stamps: prepare_prefix relinks this tool's files and Wine's update puts its own back.
+16
View File
@@ -36,6 +36,21 @@ zpath() {
esac
}
# Drive links of the prefix in compatdata folder $1 that name guest paths (DroidDeck-Proton's s: for the Steam library)
# -> their Android paths, which this Wine follows. A game's mods on S: were missing otherwise. A session's start
# gives them their guest paths back (NativeGuest.relinkPrefixDrives); z: is launch.sh's.
android_drives() {
local d t a
for d in "$1"/pfx/dosdevices/[a-y]:; do
[ -L "$d" ] || continue
t=$(readlink "$d")
case "$t" in /*) ;; *) continue ;; esac
a=$(real "$t")
[ "$a" = "$t" ] && continue
ln -sfn "$a" "$d.dd-new.$$" && mv -fT "$d.dd-new.$$" "$d" && echo "drive ${d##*/} -> $a"
done
}
# Where a game launch's log goes in DroidDeck's session folder (Share logs takes that folder): the game's log folder
# when Detailed graphics logs made one (droiddeck-game-env), else a folder of its own; nothing for other verbs
session_logs() {
@@ -109,6 +124,7 @@ print(" ".join(sorted(n for n in names if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*"
PY
)
export DROIDDECK_BIONIC_KEEP
[ -n "${STEAM_COMPAT_DATA_PATH:-}" ] && android_drives "$STEAM_COMPAT_DATA_PATH" >&2
exec /system/bin/sh "$tool/bionic/launch.sh" "$verb" "$compat" "$exe" ${args[@]+"${args[@]}"} ;;
getcompatpath)
p=$(real "${1:-}")
@@ -1,10 +0,0 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="dev.probe.npu">
<uses-sdk android:minSdkVersion="29" android:targetSdkVersion="34"/>
<application android:label="npuprobe" android:hasCode="false" android:debuggable="true">
<uses-native-library android:name="libcdsprpc.so" android:required="false"/>
<activity android:name="android.app.NativeActivity" android:exported="true">
<meta-data android:name="android.app.lib_name" android:value="npuprobe"/>
<intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter>
</activity>
</application>
</manifest>
@@ -1,18 +0,0 @@
#!/usr/bin/env bash
# Builds a Java-less NativeActivity APK that asks the vendor dspservice for a FastRPC fd and probes it.
# Usage: build.sh <out.apk>; then: adb install -r out.apk; adb shell am start -n dev.probe.npu/android.app.NativeActivity
# Results go to logcat, tag NPUPROBE.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
out=${1:?out.apk}
bt=$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -1)
work=$(mktemp -d "$HOME/.cache/npu-probe-build.XXXXXX")
trap 'rm -rf "$work"' EXIT
mkdir -p "$work/lib/arm64-v8a"
clang=$(ls -d "$NDK"/toolchains/llvm/prebuilt/*/bin)/aarch64-linux-android34-clang
"$clang" -shared -fPIC "$here/probe.c" -o "$work/lib/arm64-v8a/libnpuprobe.so" -llog -landroid -lbinder_ndk -ldl
"$bt/aapt2" link -o "$work/base.apk" --manifest "$here/AndroidManifest.xml" -I "$ANDROID_HOME/platforms/android-34/android.jar"
(cd "$work" && zip -q -u base.apk lib/arm64-v8a/libnpuprobe.so)
"$bt/zipalign" -f 4 "$work/base.apk" "$work/aligned.apk"
"$bt/apksigner" sign --ks "$HOME/.android/debug.keystore" --ks-pass pass:android --key-pass pass:android \
--ks-key-alias androiddebugkey --out "$out" "$work/aligned.apk"
-100
View File
@@ -1,100 +0,0 @@
#include <android/native_activity.h>
#include <android/log.h>
#include <android/binder_ibinder.h>
#include <android/binder_parcel.h>
#include <android/binder_status.h>
#include <dlfcn.h>
#include <stdio.h>
#include <stdint.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <string.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <sys/stat.h>
#define L(...) do { char b[600]; snprintf(b, sizeof b, __VA_ARGS__); __android_log_write(ANDROID_LOG_INFO, "NPUPROBE", b); } while (0)
static void *oc(void *a){return a;} static void od(void *a){} static binder_status_t ot(AIBinder *b, transaction_code_t c, const AParcel *i, AParcel *o){return STATUS_UNKNOWN_TRANSACTION;}
typedef uint32_t remote_handle;
/* Route A: what BananaNative does: dlopen the vendor libcdsprpc from the app namespace. */
static void route_dlopen(void) {
void *h = dlopen("libcdsprpc.so", RTLD_NOW | RTLD_LOCAL);
L("A dlopen(libcdsprpc.so) = %s", h ? "ok" : dlerror());
if (!h) return;
int (*ctl)(int, void *, uint32_t) = dlsym(h, "remote_handle_control");
int (*cap)(int, uint32_t, uint32_t *) = dlsym(h, "fastrpc_get_cap");
int (*opn)(int, const char *, remote_handle *) = dlsym(h, "remote_handle_open_domain");
L("A syms control=%p get_cap=%p open_domain=%p", ctl, cap, opn);
if (ctl) { struct { uint32_t domain, enable; } req = {3, 1}; L("A unsigned-pd control r=%d", ctl(4, &req, sizeof req)); }
if (cap) for (uint32_t i = 0; i < 3; i++) { uint32_t v = 0xdead; int r = cap(3, i, &v); L("A get_cap(cdsp,%u) r=0x%x v=%u", i, r, v); }
if (opn) { remote_handle rh = 0; errno = 0; int r = opn(3, "file:///libhalide_hexagon_remote_skel.so?halide_hexagon_initialize_kernels&_modver=1.0", &rh); L("A open_domain r=0x%x errno=%d", r, errno); }
}
static void dump_dev(AParcel *r) {
int32_t v[16]; int n = 0;
int32_t pos = AParcel_getDataPosition(r), size = AParcel_getDataSize(r);
L("reply pos=%d size=%d", pos, size);
for (int i = 0; i < 12 && AParcel_getDataPosition(r) < size; i++) { int32_t x; if (AParcel_readInt32(r, &x) != STATUS_OK) break; v[n++] = x; L(" int[%d]=%d (0x%x)", i, x, x); }
}
void ANativeActivity_onCreate(ANativeActivity *a, void *s, size_t n) {
L("uid=%d", getuid());
route_dlopen();
{ const char *nodes[] = {"/dev/fastrpc-cdsp", "/dev/adsprpc-smd"};
for (int i = 0; i < 2; i++) { int f = open(nodes[i], O_RDWR | O_CLOEXEC); L("direct open(%s) fd=%d errno=%d", nodes[i], f, errno); if (f >= 0) close(f); } }
const char *name = "vendor.qti.hardware.dsp.IDspService/default";
AIBinder *(*chk)(const char *) = dlsym(RTLD_DEFAULT, "AServiceManager_checkService");
L("dlsym checkService=%p", chk);
if (!chk) return;
AIBinder *svc = chk(name);
L("checkService(%s)=%p", name, svc);
if (!svc) { L("no service (denied or absent)"); return; }
AIBinder_Class *cs = AIBinder_Class_define("vendor.qti.hardware.dsp.IDspService", oc, od, ot);
AIBinder_associateClass(svc, cs);
AIBinder_Class *cm = AIBinder_Class_define("vendor.qti.hardware.dsp.IDspManager", oc, od, ot);
AParcel *in = NULL, *out = NULL;
AIBinder_prepareTransaction(svc, &in);
AParcel_writeInt32(in, 3);
binder_status_t st = AIBinder_transact(svc, 1, &in, &out, 0);
AStatus *as = NULL; AIBinder *mgr = NULL;
if (st == STATUS_OK) { AParcel_readStatusHeader(out, &as); AParcel_readStrongBinder(out, &mgr); }
L("getNewDSPSession: st=%d mgr=%p", st, mgr);
if (!mgr) return;
AIBinder_associateClass(mgr, cm);
int doms[] = {3, 0};
for (int di = 0; di < 2; di++) {
AParcel *i2 = NULL, *o2 = NULL;
AIBinder_prepareTransaction(mgr, &i2);
AParcel_writeInt32(i2, 1); /* non-null */
int32_t start = AParcel_getDataPosition(i2);
AParcel_writeInt32(i2, 0); AParcel_writeInt32(i2, doms[di]);
int32_t end = AParcel_getDataPosition(i2);
AParcel_setDataPosition(i2, start); AParcel_writeInt32(i2, end - start); AParcel_setDataPosition(i2, end);
st = AIBinder_transact(mgr, 2, &i2, &o2, 0);
L("openSession(domain %d): st=%d", doms[di], st);
if (st != STATUS_OK) continue;
AStatus *s2 = NULL; AParcel_readStatusHeader(o2, &s2);
L(" ex=%d", s2 ? AStatus_getExceptionCode(s2) : -1);
int32_t nn, sz, a1, b1, hsz, nf, ni;
AParcel_readInt32(o2, &nn); AParcel_readInt32(o2, &sz); AParcel_readInt32(o2, &a1); AParcel_readInt32(o2, &b1);
AParcel_readInt32(o2, &hsz); AParcel_readInt32(o2, &nf);
L(" nonnull=%d size=%d a=%d b=%d handleSize=%d nfds=%d", nn, sz, a1, b1, hsz, nf);
for (int k = 0; k < nf && k < 4; k++) {
int fd = -1; binder_status_t rs = AParcel_readParcelFileDescriptor(o2, &fd);
char path[256] = "?"; char lp[64]; snprintf(lp, sizeof lp, "/proc/self/fd/%d", fd); ssize_t r = readlink(lp, path, sizeof path - 1); if (r > 0) path[r] = 0;
L(" fd[%d]=%d (rs=%d) -> %s", k, fd, rs, path);
if (fd >= 0) {
struct { uint32_t domain, attr, cap, rsv[4]; } cap;
for (uint32_t at = 0; at < 4; at++) { cap.domain = 3; cap.attr = at; cap.cap = 0xdead; memset(cap.rsv, 0, sizeof cap.rsv); errno = 0;
int ir = ioctl(fd, _IOWR('R', 13, cap), &cap); L(" GET_DSP_INFO attr=%u r=%d errno=%d cap=%u", at, ir, errno, cap.cap); }
errno = 0; int ar = ioctl(fd, _IO('R', 4)); L(" INIT_ATTACH r=%d errno=%d", ar, errno);
uint32_t info = 3; errno = 0; int gr = ioctl(fd, _IOWR('R', 8, uint32_t), &info); L(" GETINFO(R,8) r=%d errno=%d info=%u", gr, errno, info);
}
}
AParcel_readInt32(o2, &ni);
L(" nints=%d", ni);
}
L("done");
}
+47
View File
@@ -144,6 +144,53 @@ class LaunchLog(unittest.TestCase):
self.assertIn('DXVK_LOG_PATH=${DXVK_LOG_PATH:-$COMPAT}', text)
class PrefixFromProton(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.compat = Path(self.tmp.name) / 'compatdata/236850'
self.drives = self.compat / 'pfx/dosdevices'
self.drives.mkdir(parents=True)
def test_guest_drive_links_get_android_paths(self):
for name, target in (('c:', '../drive_c'), ('s:', '/root/.local/share/Steam'), ('d:', '/mnt/sd/Steam'),
('e:', '/storage/emulated/0/Games'), ('z:', '/')):
os.symlink(target, self.drives / name)
out = proton_function('android_drives "$1"', str(self.compat))
links = {p.name: os.readlink(p) for p in self.drives.iterdir()}
self.assertEqual({'c:': '../drive_c', 's:': ANDROID + '/root/.local/share/Steam', 'd:': '/storage/1234-5678/Steam/Steam',
'e:': '/storage/emulated/0/Games', 'z:': '/'}, links)
self.assertEqual(2, len(out.splitlines()))
self.assertEqual('', proton_function('android_drives "$1"', str(self.compat)))
def test_a_prefix_without_drives_is_left_alone(self):
self.assertEqual('', proton_function('android_drives "$1"', str(Path(self.tmp.name) / 'compatdata/1')))
def steam_pid(self, reg):
text = LAUNCH.read_text()
function = text[text.index('steam_pid() {'):text.index('prefix_busy || steam_pid')]
(self.compat / 'pfx/user.reg').write_text(reg)
out = subprocess.run(['sh', '-c', function + 'steam_pid'], env=dict(os.environ, COMPAT=str(self.compat)),
capture_output=True, text=True, check=True).stdout
return out, (self.compat / 'pfx/user.reg').read_text()
def test_steams_process_id_is_this_tools(self):
reg = ('[Software\\\\Valve\\\\Steam\\\\ActiveProcess] 1795314478\n#time=1dd7a2916a0be94\n"PID"=dword:00000020\n'
'"SteamPath"="C:\\\\Program Files (x86)\\\\Steam"\n\n[Software\\\\Other] 1\n"PID"=dword:00000020\n')
out, after = self.steam_pid(reg)
self.assertIn('process ID', out)
self.assertEqual(reg.replace('"PID"=dword:00000020', '"PID"=dword:0000fffe', 1), after)
out, again = self.steam_pid(after)
self.assertEqual(('', after), (out, again))
def test_a_prefix_without_steams_key_is_unchanged(self):
reg = '[Software\\\\Wine] 1\n"PID"=dword:00000020\n'
self.assertEqual(('', reg), self.steam_pid(reg))
def test_the_network_list_uses_getifaddrs(self):
self.assertIn('export WINE_NEW_NDIS=${WINE_NEW_NDIS:-1}', LAUNCH.read_text())
class StorePaths(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
+122
View File
@@ -0,0 +1,122 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from tools.tests.test_vk_pending_completion import function
SRC = Path(__file__).resolve().parents[2] / "app/src/main/cpp/waylandcomp/src"
HARNESS = r'''
#include <assert.h>
static int g_zero_copy;
static int g_display_buffer_driver;
static int rotation;
static int game_scaled;
static int overlay_above;
static int hint;
static int hint_changes;
static int nested_composes(void) {
return overlay_above && hint == 0;
}
static int sc_layer_overlay_affordable(void) {
if (rotation <= 0) return 1;
if (nested_composes()) return 1;
return !game_scaled;
}
static int vkp_surface_rotation_degrees(void) { return rotation; }
static void droiddeck_on_overlay_planes(int planes) {
hint = planes;
hint_changes++;
}
static int g_overlay_planes_told = -1;
%(tell)s
static void frames(int n) {
for (int i = 0; i < n; i++) tell_overlay_planes();
}
static void reset(int rot, int scaled, int overlay) {
g_zero_copy = 1;
g_display_buffer_driver = 1;
rotation = rot;
game_scaled = scaled;
overlay_above = overlay;
hint = -1;
hint_changes = 0;
g_overlay_planes_told = -1;
}
int main(void) {
reset(90, 1, 1);
frames(60);
assert(hint == 0);
assert(hint_changes == 1);
overlay_above = 0;
frames(10);
overlay_above = 1;
frames(30);
assert(hint == 0);
assert(hint_changes == 1);
rotation = 0;
frames(5);
assert(hint == 1);
rotation = 90;
game_scaled = 0;
frames(30);
assert(hint == 1);
assert(hint_changes == 2);
reset(0, 1, 1);
frames(60);
assert(hint == 1 && hint_changes == 1);
reset(90, 0, 1);
frames(60);
assert(hint == 1 && hint_changes == 1);
reset(90, 1, 1);
frames(5);
assert(hint == 0);
g_zero_copy = 0;
frames(5);
assert(hint == -1);
g_zero_copy = 1;
game_scaled = 0;
frames(5);
assert(hint == 1);
return 0;
}
'''
class OverlayPlanesHintTest(unittest.TestCase):
def test_the_nested_compositor_keeps_composing_while_the_rotated_display_still_needs_it(self):
compiler = shutil.which(os.environ.get("CC", "cc"))
if not compiler:
self.fail("A C compiler is required for the overlay planes hint test")
body = function((SRC / "compositor.c").read_text(), "tell_overlay_planes")
with tempfile.TemporaryDirectory(prefix="droiddeck-overlay-planes-") as tmp:
source = Path(tmp) / "overlay_planes_hint_test.c"
source.write_text(HARNESS % {"tell": body})
program = Path(tmp) / "overlay-planes-hint"
built = subprocess.run([compiler, "-std=c11", "-Wall", "-Wextra", "-Werror", "-UNDEBUG", str(source),
"-o", str(program)], capture_output=True, text=True)
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
if __name__ == "__main__":
unittest.main()