mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-26 16:22:53 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
efc335673d | ||
|
|
497b92e63d | ||
|
|
6d6b6726fa | ||
|
|
5115b4416a | ||
|
|
a080e4a4b4 | ||
|
|
d180f563da | ||
|
|
a206be6230 |
No files matched your search
@@ -10,3 +10,6 @@ tools/mangoapp/mangoapp text eol=lf
|
||||
app/src/main/assets/desktop-removal/*.json text eol=lf
|
||||
app/src/main/assets/desktop-removal/*.txt text eol=lf
|
||||
*.pdf binary
|
||||
third_party/sdlbridge/upstream/** -text
|
||||
third_party/sdl3/upstream/** -text
|
||||
third_party/*/patches/*.patch text eol=lf
|
||||
@@ -467,7 +467,7 @@ jobs:
|
||||
path: |
|
||||
app/.cxx
|
||||
app/build/intermediates/cxx
|
||||
key: cxx-${{ env.NDK_VERSION }}-${{ hashFiles('app/src/main/cpp/**', 'tools/vr/src/xr_*.h') }}
|
||||
key: cxx-${{ env.NDK_VERSION }}-${{ hashFiles('app/src/main/cpp/**', 'third_party/sdlbridge/**', 'third_party/sdl3/**', 'tools/prepare_controller_sources.py', 'tools/vr/src/xr_*.h') }}
|
||||
restore-keys: |
|
||||
cxx-${{ env.NDK_VERSION }}-
|
||||
|
||||
|
||||
+16
-1
@@ -149,6 +149,7 @@ android {
|
||||
arguments '-DANDROID_STL=c++_shared'
|
||||
arguments "-DDROIDDECK_VITURE_SDK_DIR=${vitureSdkDir.toString().replace('\\', '/')}"
|
||||
arguments "-DDROIDDECK_UVC_DIR=${uvcDir.toString().replace('\\', '/')}"
|
||||
arguments "-DDROIDDECK_CONTROLLER_SOURCES_DIR=${layout.buildDirectory.dir('controller-sources').get().asFile.absolutePath.replace('\\', '/')}"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -275,7 +276,21 @@ if (uvcDir) {
|
||||
tasks.named('preBuild').configure { dependsOn(stageUvcNotices) }
|
||||
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('uvcAssets'))
|
||||
}
|
||||
tasks.named('preBuild').configure { dependsOn(stageRuntimeAssets) }
|
||||
def controllerSourcesDir = layout.buildDirectory.dir('controller-sources')
|
||||
def prepareControllerSources = tasks.register('prepareControllerSources', Exec) {
|
||||
inputs.dir(rootProject.file('third_party/sdlbridge'))
|
||||
inputs.dir(rootProject.file('third_party/sdl3'))
|
||||
inputs.file(rootProject.file('tools/prepare_controller_sources.py'))
|
||||
outputs.dir(controllerSourcesDir)
|
||||
workingDir rootProject.projectDir
|
||||
commandLine pythonExecutable, 'tools/prepare_controller_sources.py', '--output', controllerSourcesDir.get().asFile.absolutePath
|
||||
}
|
||||
android.sourceSets.main.java.srcDir(controllerSourcesDir.map { it.dir('sdlbridge/java') })
|
||||
android.sourceSets.main.java.srcDir(controllerSourcesDir.map { it.dir('sdl3/java') })
|
||||
tasks.configureEach { task ->
|
||||
if (task.name.startsWith('configureCMake')) task.dependsOn(prepareControllerSources)
|
||||
}
|
||||
tasks.named('preBuild').configure { dependsOn(stageRuntimeAssets, prepareControllerSources) }
|
||||
|
||||
def verifyRuntimeInputs = tasks.register('verifyRuntimeInputs', Exec) {
|
||||
mustRunAfter(stageSessionScripts, stageRuntimeAssets)
|
||||
|
||||
@@ -29,6 +29,10 @@
|
||||
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.vr.headtracking" android:version="1" android:required="false" />
|
||||
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
|
||||
<uses-feature android:name="android.hardware.usb.host" android:required="false" />
|
||||
|
||||
<application
|
||||
android:name=".App"
|
||||
android:localeConfig="@xml/locales_config"
|
||||
@@ -256,5 +260,49 @@
|
||||
android:name="backend:com.google.android.datatransport.cct.CctBackendFactory"
|
||||
tools:node="remove" />
|
||||
</service>
|
||||
|
||||
<!-- sdl3droiddeck: the SDL3 bridge, built in. SDL3 and the bridge run in their own process (":sdl3"), so a
|
||||
controller-driver crash can't take the session down; DroidDeck talks to it as to the separate app. -->
|
||||
<activity
|
||||
android:name="com.example.dsedge.BridgeActivity"
|
||||
android:process=":sdl3"
|
||||
android:exported="false"
|
||||
android:label="SDL3Bridge"
|
||||
android:launchMode="singleTop"
|
||||
android:alwaysRetainTaskState="true"
|
||||
android:taskAffinity="${applicationId}.sdl3bridge"
|
||||
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
|
||||
android:configChanges="layoutDirection|locale|orientation|uiMode|screenLayout|screenSize|smallestScreenSize|keyboard|keyboardHidden|navigation" />
|
||||
<activity
|
||||
android:name="com.example.dsedge.SdlHostActivity"
|
||||
android:process=":sdl3"
|
||||
android:exported="false"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar"
|
||||
android:configChanges="layoutDirection|locale|orientation|uiMode|screenLayout|screenSize|smallestScreenSize|keyboard|keyboardHidden|navigation" />
|
||||
<activity
|
||||
android:name="com.example.dsedge.UsbAttachActivity"
|
||||
android:process=":sdl3"
|
||||
android:exported="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:noHistory="true"
|
||||
android:taskAffinity=""
|
||||
android:theme="@android:style/Theme.NoDisplay">
|
||||
<intent-filter>
|
||||
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
|
||||
android:resource="@xml/sdl3_device_filter" />
|
||||
</activity>
|
||||
<service
|
||||
android:name="com.example.dsedge.BridgeService"
|
||||
android:process=":sdl3"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="specialUse">
|
||||
<property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="game controller bridge" />
|
||||
<intent-filter><action android:name="com.example.dsedge.BRIDGE" /></intent-filter>
|
||||
</service>
|
||||
</application>
|
||||
<uses-permission android:name="com.example.dsedge.permission.BRIDGE" />
|
||||
<queries><package android:name="com.example.dsedge" /></queries>
|
||||
</manifest>
|
||||
@@ -0,0 +1,18 @@
|
||||
Copyright (C) 1997-2026 Sam Lantinga <slouken@libsdl.org>
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
3. This notice may not be removed or altered from any source distribution.
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
repo=embedded
|
||||
tag=SdlBridge 63feeac
|
||||
sdl=3.4.18
|
||||
@@ -63,3 +63,5 @@ if(DROIDDECK_UVC_DIR)
|
||||
target_link_libraries(droiddeck_uvc PRIVATE rgb_uvc rgb_usb log)
|
||||
target_link_options(droiddeck_uvc PRIVATE -Wl,-z,max-page-size=16384)
|
||||
endif()
|
||||
|
||||
add_subdirectory(sdl3bridge)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,26 @@
|
||||
set(SDL_SHARED ON CACHE BOOL "" FORCE)
|
||||
set(SDL_STATIC OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_TEST_LIBRARY OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_TESTS OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_EXAMPLES OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_ANDROID_JAR OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_INSTALL OFF CACHE BOOL "" FORCE)
|
||||
# The bridge draws nothing (SDL3 runs headless for controllers): no OpenGL ES, so libSDL3.so needs no libGLESv1_CM.so,
|
||||
# which DroidDeck's APK check (tools/release/check_android_libraries.py) does not count as a system library.
|
||||
set(SDL_OPENGLES OFF CACHE BOOL "" FORCE)
|
||||
include(FetchContent)
|
||||
if(POLICY CMP0135)
|
||||
cmake_policy(SET CMP0135 NEW)
|
||||
endif()
|
||||
set(SDL3_MANIFEST "${DROIDDECK_CONTROLLER_SOURCES_DIR}/sdl3/upstream.json")
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${SDL3_MANIFEST}")
|
||||
file(READ "${SDL3_MANIFEST}" SDL3_UPSTREAM)
|
||||
string(JSON SDL3_ARCHIVE GET "${SDL3_UPSTREAM}" source archive)
|
||||
string(JSON SDL3_SHA256 GET "${SDL3_UPSTREAM}" source sha256)
|
||||
FetchContent_Declare(sdl3
|
||||
URL "${SDL3_ARCHIVE}"
|
||||
URL_HASH "SHA256=${SDL3_SHA256}"
|
||||
)
|
||||
FetchContent_MakeAvailable(sdl3)
|
||||
add_library(main SHARED "${DROIDDECK_CONTROLLER_SOURCES_DIR}/sdlbridge/native/main.c")
|
||||
target_link_libraries(main PRIVATE SDL3::SDL3 log)
|
||||
@@ -34,6 +34,7 @@ class App : Application() {
|
||||
com.droiddeck.launcher.stores.StoresState.init(this)
|
||||
return
|
||||
}
|
||||
if (process == "$packageName:sdl3") return // sdl3droiddeck: the SDL3 bridge's process
|
||||
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic") return
|
||||
CrashHandler.install(this)
|
||||
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
||||
|
||||
@@ -510,6 +510,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this))
|
||||
padBridge = bridge
|
||||
SessionState.padBridge = bridge
|
||||
com.droiddeck.launcher.input.DualSenseBridge.attach(this, bridge)
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
val vr = com.droiddeck.launcher.input.JoyConVr(this, File(filesDir, ".wayland-rt/${com.droiddeck.launcher.input.JoyConVr.FILE}")) { taken, released ->
|
||||
if (joyConVr == null) return@JoyConVr
|
||||
@@ -2041,6 +2042,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
if (pipUi) return true
|
||||
if (com.droiddeck.launcher.input.DualSenseBridge.isBridged(event)) return true
|
||||
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
|
||||
if (pad !== event) return dispatchKeyEvent(pad)
|
||||
val fromController = PadBridge.isControllerKeyEvent(event)
|
||||
@@ -3525,6 +3527,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
handCamera?.stop()
|
||||
handCamera = null
|
||||
padBridge?.stop()
|
||||
if (isFinishing && !SessionState.running) com.droiddeck.launcher.input.DualSenseBridge.detach(this)
|
||||
com.droiddeck.launcher.input.DualSenseBridge.screenClosed(this)
|
||||
steamController?.stop()
|
||||
if (SessionState.padBridge === padBridge) SessionState.padBridge = null
|
||||
padMotion?.stop()
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -88,7 +88,11 @@ public class FakeInputWriter {
|
||||
public static final int PAD_TYPE_XBOX = 2;
|
||||
public static final int PAD_TYPE_DS4 = 3;
|
||||
public static final int PAD_TYPE_DUALSENSE = 4;
|
||||
public static final int PAD_TYPE_DUALSENSE_EDGE = 5;
|
||||
public static final int PAD_TYPE_STEAM_2015 = 6;
|
||||
public static final int PAD_TYPE_NONE = 7;
|
||||
private static volatile int padType = -1;
|
||||
public static int currentPadType() { return padType; }
|
||||
private static volatile boolean tritonConnected = false;
|
||||
private static final int TRITON_OFFSET = RING_SIZE + 64;
|
||||
private static final int TRITON_MAGIC = 0x4e525454;
|
||||
|
||||
@@ -0,0 +1,381 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import android.system.Os
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.nio.MappedByteBuffer
|
||||
import java.nio.channels.FileChannel
|
||||
|
||||
/**
|
||||
* SDL3 bridge "Steam Native Hook-up", DroidDeck side.
|
||||
*
|
||||
* The bridge hands a USB controller over raw: its real identity and every HID report. Here each one becomes
|
||||
* /dev/hidraw24..27 -- sysfs description written like the kernel would (real vendor/product id, name, serial,
|
||||
* interface, report descriptor) and the reports moved through a file shared with fakeinput_steam.cpp
|
||||
* (FAKE_HOOKUP_SHM). Steam's own driver then runs on the real controller, like on a PC.
|
||||
*
|
||||
* Layout must match the HookupHeader / HookupSlot structs in fakeinput_steam.cpp.
|
||||
*/
|
||||
object HookupBridge {
|
||||
private const val TAG = "SessionService"
|
||||
const val FILE = ".hookup"
|
||||
private const val MAGIC = 0x4b4f4f48
|
||||
const val SLOTS = 4
|
||||
private const val IN_FIFO = 256
|
||||
private const val OUT_FIFO = 64
|
||||
private const val REPORT_MAX = 128
|
||||
private const val REPORT_SIZE = 144
|
||||
private const val DESC_MAX = 4096
|
||||
private const val HEADER_SIZE = 4096
|
||||
private const val SLOT_SIZE = 53248
|
||||
private const val SIZE = HEADER_SIZE + SLOTS * SLOT_SIZE
|
||||
private const val MINOR_BASE = 24
|
||||
private const val MAJOR = 240
|
||||
|
||||
// header
|
||||
private const val H_FF_TO_STEAM = 8
|
||||
private const val H_STEAM_MS = 16 // the Steam client's heartbeat (CLOCK_MONOTONIC ms), written by fakeinput
|
||||
private const val STEAM_GONE_MS = 5000L
|
||||
// slot
|
||||
private const val S_PRESENT = 0
|
||||
private const val S_GENERATION = 4
|
||||
private const val S_VENDOR = 8
|
||||
private const val S_PRODUCT = 10
|
||||
private const val S_VERSION = 12
|
||||
private const val S_BUS = 14
|
||||
private const val S_IFACE = 16
|
||||
private const val S_DESC_LEN = 20
|
||||
private const val S_NAME = 24
|
||||
private const val S_SERIAL = 152
|
||||
private const val S_MANUFACTURER = 216
|
||||
private const val S_PRODUCT_NAME = 280
|
||||
private const val S_IN_WRITE = 344
|
||||
private const val S_OUT_WRITE = 352
|
||||
private const val S_OUT_READ = 360
|
||||
private const val S_GET_REQUEST = 368
|
||||
private const val S_GET_REPLY = 376
|
||||
private const val S_GET_REPORT_ID = 384
|
||||
private const val S_GET_LENGTH = 388
|
||||
private const val S_GET = 392
|
||||
private const val S_DIRECT_MS = 520 // SDL3 bridge heartbeat while it serves the slot itself (fast path)
|
||||
private const val S_DESC = 1024
|
||||
private const val S_IN = 5120
|
||||
private const val S_OUT = 41984
|
||||
|
||||
@Volatile private var map: MappedByteBuffer? = null
|
||||
/** The shared file; handed to the SDL3 bridge as a descriptor so it can serve slots directly (fast path). */
|
||||
@Volatile var shmFile: File? = null
|
||||
private set
|
||||
@Volatile private var logFile: File? = null
|
||||
|
||||
/** Also written to the session's pad.log, next to the native side's "hookup:" lines. */
|
||||
internal fun note(line: String) {
|
||||
Log.i(TAG, line)
|
||||
val f = logFile ?: return
|
||||
try {
|
||||
val t = java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.US).format(java.util.Date())
|
||||
f.appendText("$t app: $line\n")
|
||||
} catch (_: Exception) {}
|
||||
}
|
||||
private val present = BooleanArray(SLOTS)
|
||||
private val getAsked = LongArray(SLOTS)
|
||||
@Volatile var tritonPassthrough = false
|
||||
set(value) { field = value; updateFfToSteam() }
|
||||
|
||||
/** Creates the shared file; returns it for FAKE_HOOKUP_SHM. Called at session start. */
|
||||
@JvmStatic
|
||||
fun prepare(fakeInputDir: File, padLog: File? = null): File? = try {
|
||||
logFile = padLog
|
||||
val file = File(fakeInputDir, FILE)
|
||||
file.delete()
|
||||
RandomAccessFile(file, "rw").use { raf ->
|
||||
raf.setLength(SIZE.toLong())
|
||||
val m = raf.channel.map(FileChannel.MapMode.READ_WRITE, 0, SIZE.toLong())
|
||||
m.order(ByteOrder.LITTLE_ENDIAN)
|
||||
m.putInt(4, 1)
|
||||
m.putInt(0, MAGIC)
|
||||
map = m
|
||||
}
|
||||
shmFile = file
|
||||
file.setReadable(true, false)
|
||||
file.setWritable(true, false)
|
||||
present.fill(false)
|
||||
note("hookup: shared file ready (${file.path}); waiting for the SDL3 bridge to hand over controllers")
|
||||
file
|
||||
} catch (e: Exception) {
|
||||
note("hookup: no shared file: $e")
|
||||
map = null
|
||||
shmFile = null
|
||||
null
|
||||
}
|
||||
|
||||
private fun slotBase(slot: Int) = HEADER_SIZE + slot * SLOT_SIZE
|
||||
|
||||
/** Inode of the shared file (0 if none): the bridge reports the one it mapped, so a stale mapping is noticed. */
|
||||
@JvmStatic fun shmInode(): Long = try { shmFile?.let { Os.stat(it.path).st_ino } ?: 0L } catch (_: Exception) { 0L }
|
||||
|
||||
/**
|
||||
* The SDL3 bridge writes this slot's reports into the file itself and takes Steam's output / feature reads
|
||||
* from it (its heartbeat is fresh): DroidDeck must leave the slot's FIFOs alone then.
|
||||
*/
|
||||
private fun bridgeServes(m: ByteBuffer, slot: Int): Boolean {
|
||||
val beat = m.getLong(slotBase(slot) + S_DIRECT_MS)
|
||||
return beat != 0L && android.os.SystemClock.uptimeMillis() - beat < 1500
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the Steam client running in this session? Its side of the hook-up writes a heartbeat into the shared file
|
||||
* every 0.1 s. (No hook-up file this session: treated as running, so nothing waits for it.)
|
||||
*/
|
||||
@JvmStatic fun steamRunning(): Boolean {
|
||||
val m = map ?: return true
|
||||
val beat = m.getLong(H_STEAM_MS)
|
||||
return beat != 0L && android.os.SystemClock.uptimeMillis() - beat < STEAM_GONE_MS
|
||||
}
|
||||
|
||||
@JvmStatic fun anyPresent(): Boolean = present.any { it }
|
||||
@JvmStatic fun isPresent(slot: Int): Boolean = slot in 0 until SLOTS && present[slot]
|
||||
|
||||
/** True while Steam is handed game rumble (a real controller it drives itself is present). */
|
||||
@JvmStatic fun ffToSteam(): Boolean = map != null && (anyPresent() || tritonPassthrough)
|
||||
|
||||
private fun updateFfToSteam() {
|
||||
val m = map ?: return
|
||||
synchronized(this) {
|
||||
FakeInputWriter.storeFence()
|
||||
m.putInt(H_FF_TO_STEAM, if (anyPresent() || tritonPassthrough) 1 else 0)
|
||||
}
|
||||
}
|
||||
|
||||
private fun putString(m: ByteBuffer, at: Int, max: Int, s: String) {
|
||||
val b = s.toByteArray(Charsets.UTF_8)
|
||||
val n = minOf(b.size, max - 1)
|
||||
for (i in 0 until max) m.put(at + i, if (i < n) b[i] else 0)
|
||||
}
|
||||
|
||||
// ---------------- bridge messages (DualSenseBridge's worker thread) ----------------
|
||||
|
||||
@Synchronized
|
||||
fun add(id: Bundle) {
|
||||
val m = map ?: run {
|
||||
note("hookup: the bridge handed over a controller but this session has no hook-up file " +
|
||||
"(DroidDeck build without it, or the session started without the deck pad)")
|
||||
return
|
||||
}
|
||||
val slot = id.getInt("slot", -1)
|
||||
if (slot !in 0 until SLOTS) { note("hookup: the bridge handed over slot $slot, which does not exist"); return }
|
||||
val base = slotBase(slot)
|
||||
val desc = id.getByteArray("desc") ?: ByteArray(0)
|
||||
if (present[slot] && (m.getShort(base + S_VENDOR).toInt() and 0xffff) == id.getInt("vid") &&
|
||||
(m.getShort(base + S_PRODUCT).toInt() and 0xffff) == id.getInt("pid") && m.getInt(base + S_IFACE) == id.getInt("iface")) {
|
||||
return // the same controller resent after a reconnect: keep it as it is (no unplug/replug in Steam)
|
||||
}
|
||||
if (present[slot]) remove(slot)
|
||||
describeSysfs(slot, id, desc)
|
||||
m.putShort(base + S_VENDOR, id.getInt("vid").toShort())
|
||||
m.putShort(base + S_PRODUCT, id.getInt("pid").toShort())
|
||||
m.putShort(base + S_VERSION, id.getInt("version").toShort())
|
||||
m.putShort(base + S_BUS, id.getInt("bus", 3).toShort())
|
||||
m.putInt(base + S_IFACE, id.getInt("iface"))
|
||||
putString(m, base + S_NAME, 128, id.getString("name") ?: "")
|
||||
putString(m, base + S_SERIAL, 64, id.getString("serial") ?: "")
|
||||
putString(m, base + S_MANUFACTURER, 64, id.getString("manufacturer") ?: "")
|
||||
putString(m, base + S_PRODUCT_NAME, 64, id.getString("product") ?: "")
|
||||
val n = minOf(desc.size, DESC_MAX)
|
||||
for (i in 0 until n) m.put(base + S_DESC + i, desc[i])
|
||||
m.putInt(base + S_DESC_LEN, n)
|
||||
// fresh FIFOs: the readers start at the current write position, so only the counters matter
|
||||
m.putLong(base + S_OUT_READ, m.getLong(base + S_OUT_WRITE))
|
||||
getAsked[slot] = m.getLong(base + S_GET_REQUEST)
|
||||
m.putLong(base + S_GET_REPLY, getAsked[slot])
|
||||
m.putInt(base + S_GENERATION, m.getInt(base + S_GENERATION) + 1)
|
||||
FakeInputWriter.storeFence()
|
||||
m.putInt(base + S_PRESENT, 1)
|
||||
present[slot] = true
|
||||
updateFfToSteam()
|
||||
note("hookup: /dev/hidraw${MINOR_BASE + slot} = %04x:%04x \"%s\" interface %d, descriptor %d bytes (Steam Native Hook-up)"
|
||||
.format(id.getInt("vid"), id.getInt("pid"), id.getString("name"), id.getInt("iface"), desc.size))
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun input(slot: Int, data: ByteArray) {
|
||||
val m = map ?: return
|
||||
if (slot !in 0 until SLOTS || !present[slot] || data.isEmpty()) return
|
||||
if (bridgeServes(m, slot)) return // a late message from before the fast path took over
|
||||
val base = slotBase(slot)
|
||||
val idx = m.getLong(base + S_IN_WRITE)
|
||||
val at = base + S_IN + ((idx % IN_FIFO).toInt()) * REPORT_SIZE
|
||||
m.putLong(at, 0L)
|
||||
FakeInputWriter.storeFence()
|
||||
val n = minOf(data.size, REPORT_MAX)
|
||||
m.putInt(at + 8, n)
|
||||
m.putInt(at + 12, 0)
|
||||
for (i in 0 until n) m.put(at + 16 + i, data[i])
|
||||
FakeInputWriter.storeFence()
|
||||
m.putLong(at, idx + 1)
|
||||
m.putLong(base + S_IN_WRITE, idx + 1)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun remove(slot: Int) {
|
||||
val m = map ?: return
|
||||
if (slot !in 0 until SLOTS) return
|
||||
m.putInt(slotBase(slot) + S_PRESENT, 0)
|
||||
m.putLong(slotBase(slot) + S_DIRECT_MS, 0L)
|
||||
FakeInputWriter.storeFence()
|
||||
if (present[slot]) note("hookup: /dev/hidraw${MINOR_BASE + slot} unplugged")
|
||||
present[slot] = false
|
||||
unlinkClass(slot)
|
||||
updateFfToSteam()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun removeAll() { for (s in 0 until SLOTS) if (present[s]) remove(s) }
|
||||
|
||||
@Synchronized
|
||||
fun reply(slot: Int, request: Long, data: ByteArray?) {
|
||||
val m = map ?: return
|
||||
if (slot !in 0 until SLOTS || request != getAsked[slot]) return
|
||||
val base = slotBase(slot)
|
||||
val n = if (data == null) 0 else minOf(data.size, REPORT_MAX)
|
||||
for (i in 0 until n) m.put(base + S_GET + i, data!![i])
|
||||
m.putInt(base + S_GET_LENGTH, n)
|
||||
FakeInputWriter.storeFence()
|
||||
m.putLong(base + S_GET_REPLY, request)
|
||||
}
|
||||
|
||||
/**
|
||||
* Steam -> controller. Calls [out](slot, kind, report) for each queued output report / feature write and
|
||||
* [get](slot, request, reportId, input, length) for a new feature/input read. Run every ~1 ms.
|
||||
*/
|
||||
@Synchronized
|
||||
fun poll(out: (Int, Int, ByteArray) -> Unit, get: (Int, Long, Int, Boolean, Int) -> Unit) {
|
||||
val m = map ?: return
|
||||
for (slot in 0 until SLOTS) {
|
||||
if (!present[slot]) continue
|
||||
FakeInputWriter.storeFence()
|
||||
if (bridgeServes(m, slot)) continue // the bridge takes Steam's reports from the file itself
|
||||
val base = slotBase(slot)
|
||||
var read = m.getLong(base + S_OUT_READ)
|
||||
val written = m.getLong(base + S_OUT_WRITE)
|
||||
while (read < written) {
|
||||
val at = base + S_OUT + ((read % OUT_FIFO).toInt()) * REPORT_SIZE
|
||||
if (m.getLong(at) != read + 1) break // still being written
|
||||
val n = m.getInt(at + 8).coerceIn(0, REPORT_MAX)
|
||||
val kind = m.getInt(at + 12)
|
||||
val data = ByteArray(n)
|
||||
for (i in 0 until n) data[i] = m.get(at + 16 + i)
|
||||
read++
|
||||
if (n > 0) out(slot, kind, data)
|
||||
}
|
||||
m.putLong(base + S_OUT_READ, read)
|
||||
val request = m.getLong(base + S_GET_REQUEST)
|
||||
if (request != getAsked[slot] && request != m.getLong(base + S_GET_REPLY)) {
|
||||
getAsked[slot] = request
|
||||
val idWord = m.getInt(base + S_GET_REPORT_ID)
|
||||
get(slot, request, idWord and 0xff, (idWord and 0x100) != 0, m.getInt(base + S_GET_LENGTH))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- sysfs, as Linux would describe the device ----------------
|
||||
|
||||
private fun guestHid(slot: Int, id: Bundle): Triple<String, String, String> {
|
||||
val bus = 10 + slot
|
||||
val usb = "/sys/devices/droiddeck/usb$bus"
|
||||
val iface = "$usb/$bus-1:1.${maxOf(0, id.getInt("iface"))}"
|
||||
val hid = "$iface/0003:%04X:%04X.%04X".format(id.getInt("vid"), id.getInt("pid"), 0x10 + slot)
|
||||
return Triple(usb, iface, hid)
|
||||
}
|
||||
|
||||
private fun describeSysfs(slot: Int, id: Bundle, desc: ByteArray) {
|
||||
val devices = com.droiddeck.launcher.session.SteamDeckPad.sysDevicesDir
|
||||
val classDir = com.droiddeck.launcher.session.SteamDeckPad.sysHidrawClassDir
|
||||
val context = com.droiddeck.launcher.session.SteamDeckPad.sysContext
|
||||
if (devices == null || classDir == null || context == null) {
|
||||
note("hookup: no session sysfs to describe /dev/hidraw${MINOR_BASE + slot} in (deck pad off?)")
|
||||
return
|
||||
}
|
||||
try {
|
||||
val (usb, iface, hid) = guestHid(slot, id)
|
||||
fun dir(guest: String) = File(devices, guest.removePrefix("/sys/devices/droiddeck/")).apply { mkdirs() }
|
||||
fun write(guest: String, name: String, text: String) = File(dir(guest), name).writeText(text)
|
||||
fun link(file: File, target: String) {
|
||||
file.parentFile?.mkdirs()
|
||||
file.delete()
|
||||
Os.symlink(target, file.path)
|
||||
}
|
||||
deleteTree(File(devices, usb.removePrefix("/sys/devices/droiddeck/"))) // the previous description
|
||||
val vid = id.getInt("vid")
|
||||
val pid = id.getInt("pid")
|
||||
val ver = id.getInt("version")
|
||||
val vidHex = "%04x".format(vid)
|
||||
val pidHex = "%04x".format(pid)
|
||||
val product = "%x/%x/%x".format(vid, pid, ver)
|
||||
val node = "hidraw${MINOR_BASE + slot}"
|
||||
val minor = MINOR_BASE + slot
|
||||
val busNum = "%03d".format(10 + slot)
|
||||
write(usb, "uevent", "DEVTYPE=usb_device\nPRODUCT=$product\nTYPE=0/0/0\nBUSNUM=$busNum\nDEVNUM=002\n")
|
||||
write(usb, "idVendor", "$vidHex\n")
|
||||
write(usb, "idProduct", "$pidHex\n")
|
||||
write(usb, "bcdDevice", "%04x\n".format(ver))
|
||||
write(usb, "manufacturer", "${id.getString("manufacturer") ?: ""}\n")
|
||||
write(usb, "product", "${id.getString("product") ?: ""}\n")
|
||||
write(usb, "serial", "${id.getString("serial") ?: ""}\n")
|
||||
write(usb, "busnum", "${10 + slot}\n")
|
||||
write(usb, "devnum", "2\n")
|
||||
link(File(dir(usb), "subsystem"), "/sys/bus/usb")
|
||||
val cls = id.getInt("ifclass", 3)
|
||||
write(iface, "uevent", "DEVTYPE=usb_interface\nPRODUCT=$product\nINTERFACE=$cls/${id.getInt("ifsub")}/${id.getInt("ifproto")}\n")
|
||||
write(iface, "bInterfaceNumber", "%02x\n".format(maxOf(0, id.getInt("iface"))))
|
||||
write(iface, "bInterfaceClass", "%02x\n".format(cls))
|
||||
write(iface, "bInterfaceSubClass", "%02x\n".format(id.getInt("ifsub")))
|
||||
write(iface, "bInterfaceProtocol", "%02x\n".format(id.getInt("ifproto")))
|
||||
link(File(dir(iface), "subsystem"), "/sys/bus/usb")
|
||||
val name = id.getString("name") ?: ""
|
||||
val serial = id.getString("serial") ?: ""
|
||||
write(hid, "uevent", "DRIVER=hid-generic\nHID_ID=0003:%08X:%08X\nHID_NAME=$name\n".format(vid, pid) +
|
||||
"HID_PHYS=usb-droiddeck-${10 + slot}/input${maxOf(0, id.getInt("iface"))}\nHID_UNIQ=$serial\n" +
|
||||
"MODALIAS=hid:b0003g0001v%08Xp%08X\n".format(vid, pid))
|
||||
File(dir(hid), "report_descriptor").writeBytes(desc)
|
||||
link(File(dir(hid), "subsystem"), "/sys/bus/hid")
|
||||
val hidraw = "$hid/hidraw/$node"
|
||||
write(hidraw, "uevent", "MAJOR=$MAJOR\nMINOR=$minor\nDEVNAME=$node\n")
|
||||
write(hidraw, "dev", "$MAJOR:$minor\n")
|
||||
link(File(dir(hidraw), "subsystem"), "/sys/class/hidraw")
|
||||
link(File(dir(hidraw), "device"), hid)
|
||||
link(File(classDir, node), hidraw)
|
||||
link(File(LinuxRuntime.liveDir(context), "drm/sys/$MAJOR:$minor"), hidraw)
|
||||
val udevData = File(LinuxRuntime.rootDir(context), "run/udev/data").apply { mkdirs() }
|
||||
File(udevData, "c$MAJOR:$minor").writeText("I:1\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\n")
|
||||
} catch (e: Exception) {
|
||||
note("hookup: could not describe /dev/hidraw${MINOR_BASE + slot}: $e")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a folder without following symbolic links. (File.deleteRecursively() follows them: the description
|
||||
* links "subsystem" to the phone's real /sys/bus/..., and walking into the real /sys -- full of links back into
|
||||
* itself -- never ends, which froze DroidDeck's bridge thread on the second hand-over of a controller.)
|
||||
*/
|
||||
private fun deleteTree(f: File) {
|
||||
val st = try { Os.lstat(f.path) } catch (_: Exception) { return } // gone already
|
||||
if (android.system.OsConstants.S_ISDIR(st.st_mode)) f.list()?.forEach { deleteTree(File(f, it)) }
|
||||
f.delete()
|
||||
}
|
||||
|
||||
private fun unlinkClass(slot: Int) {
|
||||
val classDir = com.droiddeck.launcher.session.SteamDeckPad.sysHidrawClassDir ?: return
|
||||
try { File(classDir, "hidraw${MINOR_BASE + slot}").delete() } catch (_: Exception) {}
|
||||
}
|
||||
|
||||
/** True when DroidDeck should set the hook-up file up this session (the bridge app is installed). */
|
||||
@JvmStatic fun wanted(context: Context): Boolean =
|
||||
com.droiddeck.launcher.session.SessionPrefs.sdl3Controllers(context) && DualSenseBridge.isBridgeInstalled(context)
|
||||
}
|
||||
@@ -51,6 +51,7 @@ public final class PadBridge {
|
||||
private volatile java.util.function.IntPredicate excluded = id -> false;
|
||||
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
|
||||
private final PadState[] playerStates = new PadState[SLOTS];
|
||||
private final boolean[] bridgeSlots = new boolean[SLOTS]; // slots fed by the SDL3 bridge app
|
||||
private final PadState effectiveState = new PadState();
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
private boolean open;
|
||||
@@ -200,6 +201,7 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
public static boolean isControllerKeyEvent(KeyEvent event) {
|
||||
if (DualSenseBridge.isBridged(event)) return false;
|
||||
InputDevice device = event.getDevice();
|
||||
if (device == null || device.isVirtual() || isSystemVirtualInputName(device.getName())) return false;
|
||||
if (KeyEvent.isGamepadButton(event.getKeyCode())) {
|
||||
@@ -224,6 +226,7 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
public static boolean isControllerMotionEvent(MotionEvent event) {
|
||||
if (DualSenseBridge.isBridged(event)) return false;
|
||||
InputDevice device = event.getDevice();
|
||||
return event.isFromSource(InputDevice.SOURCE_JOYSTICK) && device != null && !device.isVirtual()
|
||||
&& !isSystemVirtualInputName(device.getName())
|
||||
@@ -446,6 +449,39 @@ public final class PadBridge {
|
||||
publish();
|
||||
}
|
||||
|
||||
/** SDL3 bridge: reserves a free player slot (1..3) for an extra controller. @return the slot, or -1 if none is free. */
|
||||
public synchronized int claimBridgeSlot() {
|
||||
for (int slot = 1; slot < SLOTS; slot++) {
|
||||
if (owners[slot] != NO_CONTROLLER || bridgeSlots[slot]) continue;
|
||||
bridgeSlots[slot] = true;
|
||||
playerStates[slot].clear();
|
||||
Log.i(TAG, "SDL3 bridge controller is player " + (slot + 1));
|
||||
return slot;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** SDL3 bridge: frees a slot taken with {@link #claimBridgeSlot()}. */
|
||||
public synchronized void releaseBridgeSlot(int slot) {
|
||||
if (slot < 1 || slot >= SLOTS || !bridgeSlots[slot]) return;
|
||||
bridgeSlots[slot] = false;
|
||||
playerStates[slot].clear();
|
||||
if (playerWriters[slot] != null) {
|
||||
playerWriters[slot].destroy();
|
||||
playerWriters[slot] = null;
|
||||
}
|
||||
Log.i(TAG, "SDL3 bridge player " + (slot + 1) + " left");
|
||||
}
|
||||
|
||||
/** SDL3 bridge: updates player [slot] (0 = primary pad, 1..3 = claimed bridge slots). */
|
||||
public synchronized void applyExternalSlot(int slot, java.util.function.Consumer<PadState> mutation, boolean changed) {
|
||||
if (slot <= 0) { applyExternal(mutation, changed); return; }
|
||||
if (slot >= SLOTS || !bridgeSlots[slot]) return;
|
||||
mutation.accept(playerStates[slot]);
|
||||
if (changed) notePlayerInput();
|
||||
publish(slot);
|
||||
}
|
||||
|
||||
public synchronized void setSystemButtons(boolean guidePressed, boolean qamPressed) {
|
||||
if (!builtinPad) return;
|
||||
if (systemGuidePressed == guidePressed && systemQamPressed == qamPressed) return;
|
||||
@@ -561,7 +597,7 @@ public final class PadBridge {
|
||||
return slot;
|
||||
}
|
||||
for (int slot = firstPlayerSlot(); slot < SLOTS; slot++) {
|
||||
if (owners[slot] != NO_CONTROLLER) continue;
|
||||
if (owners[slot] != NO_CONTROLLER || bridgeSlots[slot]) continue;
|
||||
owners[slot] = id;
|
||||
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") is player " + (slot + 1));
|
||||
return slot;
|
||||
|
||||
@@ -62,7 +62,7 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
|
||||
val wanted = FakeInputWriter.readImuMode(SLOT) != 0 ||
|
||||
touch != null && touch.plugged && touch.gyroRequested && touch.motionEnabled
|
||||
idlePolls = if (wanted) 0 else idlePolls + 1
|
||||
if (wanted && !reading) {
|
||||
if (wanted && !DualSenseBridge.isActive() && !reading) {
|
||||
reading = true
|
||||
turnAt = 0L
|
||||
gyroscope?.let { sensors?.registerListener(this, it, SAMPLING_US, handler) }
|
||||
@@ -83,6 +83,7 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
|
||||
}
|
||||
|
||||
override fun onSensorChanged(event: SensorEvent) {
|
||||
if (DualSenseBridge.isActive()) return
|
||||
if (!active) return
|
||||
val values = event.values
|
||||
if (event.timestamp - turnAt > ROTATION_REFRESH_NS) {
|
||||
|
||||
@@ -37,6 +37,7 @@ class RumbleComponent : SessionPart() {
|
||||
}
|
||||
|
||||
internal var controllerMotors: (Int) -> Motors? = ::lookupController
|
||||
internal var bridgeRumble: (Int, Int, Int, Int) -> Boolean = com.droiddeck.launcher.input.DualSenseBridge::routeRumble
|
||||
internal var motorLooper: Looper? = null
|
||||
|
||||
@Synchronized private fun refreshEnabled() {
|
||||
@@ -90,6 +91,11 @@ class RumbleComponent : SessionPart() {
|
||||
|
||||
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) {
|
||||
if (!enabled) return
|
||||
if (bridgeRumble(slot, strong, weak, ms)) {
|
||||
playing.remove(slot)?.cancel()
|
||||
forget(slot)
|
||||
return
|
||||
}
|
||||
val target = target(slot)
|
||||
val previous = playing[slot]
|
||||
if (target !== previous) {
|
||||
|
||||
@@ -42,6 +42,12 @@ object SessionPrefs {
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
|
||||
fun sdl3Controllers(context: Context): Boolean = prefs(context).getBoolean("sdl3Controllers", false)
|
||||
|
||||
fun setSdl3Controllers(context: Context, enabled: Boolean) {
|
||||
prefs(context).edit().putBoolean("sdl3Controllers", enabled).apply()
|
||||
}
|
||||
|
||||
val orientationOptions = listOf(
|
||||
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE to R.string.setup_orientation_auto,
|
||||
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE to R.string.setup_orientation_landscape,
|
||||
|
||||
@@ -169,6 +169,7 @@ class SessionService : Service() {
|
||||
updateSuspendPolicy()
|
||||
}
|
||||
@Volatile private var sessionGen = 0
|
||||
private var bridgeSession: Any? = null
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
@@ -314,6 +315,7 @@ class SessionService : Service() {
|
||||
}
|
||||
startForeground(NOTIFICATION_ID, buildNotification())
|
||||
if (SessionState.running) return START_NOT_STICKY
|
||||
bridgeSession = Any().also { com.droiddeck.launcher.input.DualSenseBridge.beginSession(it) }
|
||||
if (SessionState.stopRequested) {
|
||||
SessionState.running = true
|
||||
stopSession(0)
|
||||
@@ -815,14 +817,21 @@ class SessionService : Service() {
|
||||
guest.add("FAKE_EVDEV_IDENTITY=xbox360")
|
||||
guest.add("FAKE_EVDEV_VIBRATION=1")
|
||||
val uinput = !File(Environment.getExternalStorageDirectory(), NO_UINPUT_SWITCH).exists()
|
||||
val wantsDeck = uinput && builtinPad && SessionState.mode == MODE_STEAM &&
|
||||
SessionState.steamUi != "desktop" &&
|
||||
// sdl3bridge: the desktop (and Steam's desktop UI) get the deck pad too while the SDL3 bridge is installed,
|
||||
// so its "present as" types and Steam Native Hook-up work there like in the Steam session
|
||||
val sdl3Desktop = (SessionState.mode == MODE_DESKTOP ||
|
||||
(SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop")) &&
|
||||
com.droiddeck.launcher.input.HookupBridge.wanted(this)
|
||||
val wantsDeck = uinput && builtinPad && (SessionState.mode == MODE_STEAM &&
|
||||
SessionState.steamUi != "desktop" || sdl3Desktop) &&
|
||||
!File(Environment.getExternalStorageDirectory(), NO_DECK_PAD_SWITCH).exists()
|
||||
val wantsTouch = wantsDeck && !File(Environment.getExternalStorageDirectory(), NO_STEAM_TOUCH_SWITCH).exists()
|
||||
val wantsTriton = wantsDeck && SteamControllerBle.hasPairedController(this)
|
||||
val wantsTouch = wantsDeck && !sdl3Desktop && !File(Environment.getExternalStorageDirectory(), NO_STEAM_TOUCH_SWITCH).exists()
|
||||
val wantsTriton = wantsDeck && (SteamControllerBle.hasPairedController(this) || com.droiddeck.launcher.input.HookupBridge.wanted(this))
|
||||
deckBinds = if (wantsDeck) SteamDeckPad.prepare(this, fakeInputDir.parentFile!!.parentFile!!, wantsTouch, wantsTriton,
|
||||
SessionPrefs.padType(SessionPrefs.steamController(this))) else emptyList()
|
||||
SessionState.deckPad = deckBinds.isNotEmpty()
|
||||
if (sdl3Desktop && SessionState.deckPad) Log.i(TAG, "deck pad: on for the SDL3 bridge on the desktop " +
|
||||
"(Steam gets the controller as the bridge presents it; other programs keep Xbox 360 pads)")
|
||||
if (wantsDeck && !SessionState.deckPad) Log.w(TAG, "deck pad: not available this session; the pad stays an Xbox 360 controller")
|
||||
logControllersAtStart()
|
||||
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(SessionPrefs.lowLatencyController(this), SessionPrefs.lowLatencyTouch(this))
|
||||
@@ -830,6 +839,7 @@ class SessionService : Service() {
|
||||
guest.add("FAKE_EVDEV_UINPUT=1")
|
||||
if (SessionState.deckPad) {
|
||||
guest.add("FAKE_EVDEV_DECK=1")
|
||||
if (SessionState.mode == MODE_DESKTOP) guest.add("FAKE_EVDEV_DESKTOP=1") // sdl3bridge
|
||||
if (wantsTriton) guest.add("FAKE_EVDEV_TRITON=1")
|
||||
val padType = SessionPrefs.steamController(this)
|
||||
guest.add("FAKE_EVDEV_PAD_TYPE=$padType")
|
||||
@@ -838,6 +848,8 @@ class SessionService : Service() {
|
||||
if (wantsTouch) com.droiddeck.launcher.input.SteamTouchDevice.prepare(fakeInputDir)?.let {
|
||||
guest.add("FAKE_TOUCHCTL_RING=" + it.path)
|
||||
}
|
||||
if (com.droiddeck.launcher.input.HookupBridge.wanted(this))
|
||||
com.droiddeck.launcher.input.HookupBridge.prepare(fakeInputDir, File(sessionDir, "pad.log"))?.let { guest.add("FAKE_HOOKUP_SHM=" + it.path) }
|
||||
guest.add("FAKE_DECK_SYSFS_LISTING=" + SteamDeckPad.listingDir(fakeInputDir.parentFile!!.parentFile!!).path)
|
||||
}
|
||||
} else if (SessionState.mode == MODE_STEAM) {
|
||||
@@ -849,7 +861,7 @@ class SessionService : Service() {
|
||||
guest.add("FAKE_EVDEV_LOG=1")
|
||||
guest.add("FAKE_EVDEV_LOG_FILE=" + File(sessionDir, "pad.log").path)
|
||||
inputSysfs = InputSysfsComponent(fakeInputDir, File(fakeInputDir.parentFile!!.parentFile!!, "sys/input"),
|
||||
File(LinuxRuntime.rootDir(this), "run/udev/data"), SessionState.deckPad, !uinput && SessionState.mode == MODE_STEAM)
|
||||
File(LinuxRuntime.rootDir(this), "run/udev/data"), SessionState.deckPad && SessionState.mode != MODE_DESKTOP, !uinput && SessionState.mode == MODE_STEAM)
|
||||
.takeIf { it.prepare() }
|
||||
SessionState.fakeInputDir = fakeInputDir
|
||||
}
|
||||
@@ -1676,6 +1688,8 @@ class SessionService : Service() {
|
||||
SessionEvents.record("guest.exited", mapOf("status" to status))
|
||||
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
|
||||
SessionState.running = false
|
||||
bridgeSession?.let { com.droiddeck.launcher.input.DualSenseBridge.endSession(it) }
|
||||
bridgeSession = null
|
||||
SessionPaths.take() to SessionState.steamClientArch
|
||||
}
|
||||
SessionState.micAvailable = false
|
||||
@@ -1761,6 +1775,8 @@ class SessionService : Service() {
|
||||
override fun onDestroy() {
|
||||
stopSession(0)
|
||||
GameThreadHints.stop() // also when the session never got as far as running
|
||||
bridgeSession?.let { com.droiddeck.launcher.input.DualSenseBridge.endSession(it) }
|
||||
bridgeSession = null
|
||||
if (screenReceiverRegistered) {
|
||||
unregisterReceiver(screenReceiver)
|
||||
screenReceiverRegistered = false
|
||||
|
||||
@@ -27,6 +27,8 @@ object SteamDeckPad {
|
||||
private const val TRITON_WIRED_HID = "$TRITON_INTERFACE/0003:28DE:1302.0004"
|
||||
private const val SONY_DS4_MINOR = 20
|
||||
private const val SONY_DUALSENSE_MINOR = 21
|
||||
private const val SONY_DUALSENSE_EDGE_MINOR = 22
|
||||
private const val SC2015_MINOR = 23
|
||||
private val DS4_REPORT_DESCRIPTOR = intArrayOf(
|
||||
0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x06, 0x00, 0xff, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08,
|
||||
0x85, 0x01, 0x09, 0x20, 0x95, 0x3f, 0x81, 0x02, 0x85, 0x05, 0x09, 0x21, 0x95, 0x1f, 0x91, 0x02,
|
||||
@@ -82,6 +84,10 @@ object SteamDeckPad {
|
||||
|
||||
fun listingDir(sessionRoot: File) = File(sessionRoot, "sys/deck/listing")
|
||||
|
||||
// sdl3bridge: where the session sysfs lives, for HookupBridge (Steam Native Hook-up) hot-plug
|
||||
@Volatile @JvmStatic var sysDevicesDir: File? = null
|
||||
@Volatile @JvmStatic var sysHidrawClassDir: File? = null
|
||||
@Volatile @JvmStatic var sysContext: Context? = null
|
||||
private val padNodes = mutableMapOf<Int, String>()
|
||||
@Volatile private var hidrawClassDir: File? = null
|
||||
|
||||
@@ -93,6 +99,8 @@ object SteamDeckPad {
|
||||
com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_STEAM -> TRITON_PAD_MINOR
|
||||
com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_DS4 -> SONY_DS4_MINOR
|
||||
com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_DUALSENSE -> SONY_DUALSENSE_MINOR
|
||||
com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_DUALSENSE_EDGE -> SONY_DUALSENSE_EDGE_MINOR
|
||||
com.droiddeck.launcher.input.FakeInputWriter.PAD_TYPE_STEAM_2015 -> SC2015_MINOR
|
||||
else -> -1
|
||||
}
|
||||
for ((minor, target) in padNodes) {
|
||||
@@ -224,12 +232,8 @@ object SteamDeckPad {
|
||||
File(udevData, "c$MAJOR:$minor").writeText("I:1\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\n")
|
||||
Log.i(TAG, "steam controller: /dev/$node described as Triton (28de:$product)")
|
||||
}
|
||||
fun describeSony(dualSense: Boolean) {
|
||||
val bus = if (dualSense) 5 else 4
|
||||
val product = if (dualSense) "0ce6" else "09cc"
|
||||
val minor = if (dualSense) SONY_DUALSENSE_MINOR else SONY_DS4_MINOR
|
||||
fun describeSony(bus: Int, product: String, minor: Int, name: String, sonyDescriptor: ByteArray) {
|
||||
val node = "hidraw$minor"
|
||||
val name = if (dualSense) "DualSense Wireless Controller" else "Wireless Controller"
|
||||
val usb = "$GUEST_DEVICES/usb$bus"
|
||||
val iface = "$usb/$bus-1:1.3"
|
||||
val hid = "$iface/0003:054C:${product.uppercase()}.000${bus + 1}"
|
||||
@@ -247,7 +251,7 @@ object SteamDeckPad {
|
||||
write(hid, "uevent", "DRIVER=hid-generic\nHID_ID=0003:0000054C:0000${product.uppercase()}\n" +
|
||||
"HID_NAME=Sony Interactive Entertainment $name\nHID_PHYS=usb-droiddeck-$bus/input3\n" +
|
||||
"HID_UNIQ=5e:43:4b:44:44:02\nMODALIAS=hid:b0003g0001v0000054Cp0000${product.uppercase()}\n")
|
||||
File(dir(hid), "report_descriptor").writeBytes(if (dualSense) DUALSENSE_REPORT_DESCRIPTOR else DS4_REPORT_DESCRIPTOR)
|
||||
File(dir(hid), "report_descriptor").writeBytes(sonyDescriptor)
|
||||
link(File(dir(hid), "subsystem"), "/sys/bus/hid")
|
||||
val hidraw = "$hid/hidraw/$node"
|
||||
write(hidraw, "uevent", "MAJOR=$MAJOR\nMINOR=$minor\nDEVNAME=$node\n")
|
||||
@@ -259,11 +263,48 @@ object SteamDeckPad {
|
||||
File(udevData, "c$MAJOR:$minor").writeText("I:1\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\n")
|
||||
Log.i(TAG, "playstation pad: /dev/$node described as 054c:$product")
|
||||
}
|
||||
describeSony(dualSense = false)
|
||||
describeSony(dualSense = true)
|
||||
describeSony(4, "09cc", SONY_DS4_MINOR, "Wireless Controller", DS4_REPORT_DESCRIPTOR)
|
||||
describeSony(5, "0ce6", SONY_DUALSENSE_MINOR, "DualSense Wireless Controller", DUALSENSE_REPORT_DESCRIPTOR)
|
||||
describeSony(6, "0df2", SONY_DUALSENSE_EDGE_MINOR, "DualSense Edge Wireless Controller", DUALSENSE_REPORT_DESCRIPTOR)
|
||||
fun describeSteamController2015() {
|
||||
val usb = "$GUEST_DEVICES/usb7"
|
||||
val iface = "$usb/7-1:1.2"
|
||||
val hid = "$iface/0003:28DE:1102.0008"
|
||||
val node = "hidraw$SC2015_MINOR"
|
||||
write(usb, "uevent", "DEVTYPE=usb_device\nPRODUCT=28de/1102/100\nTYPE=0/0/0\nBUSNUM=007\nDEVNUM=002\n")
|
||||
write(usb, "idVendor", "28de\n")
|
||||
write(usb, "idProduct", "1102\n")
|
||||
write(usb, "bcdDevice", "0100\n")
|
||||
write(usb, "manufacturer", "Valve Software\n")
|
||||
write(usb, "product", "Steam Controller\n")
|
||||
write(usb, "serial", "DROIDDECKSC15\n")
|
||||
link(File(dir(usb), "subsystem"), "/sys/bus/usb")
|
||||
write(iface, "uevent", "DEVTYPE=usb_interface\nPRODUCT=28de/1102/100\nINTERFACE=3/0/0\n")
|
||||
write(iface, "bInterfaceNumber", "02\n")
|
||||
write(iface, "bInterfaceClass", "03\n")
|
||||
link(File(dir(iface), "subsystem"), "/sys/bus/usb")
|
||||
write(hid, "uevent", "DRIVER=hid-steam\nHID_ID=0003:000028DE:00001102\n" +
|
||||
"HID_NAME=Valve Software Steam Controller\nHID_PHYS=usb-droiddeck-7/input2\n" +
|
||||
"HID_UNIQ=DROIDDECKSC15\nMODALIAS=hid:b0003g0001v000028DEp00001102\n")
|
||||
File(dir(hid), "report_descriptor").writeBytes(REPORT_DESCRIPTOR)
|
||||
link(File(dir(hid), "subsystem"), "/sys/bus/hid")
|
||||
val hidraw = "$hid/hidraw/$node"
|
||||
write(hidraw, "uevent", "MAJOR=$MAJOR\nMINOR=$SC2015_MINOR\nDEVNAME=$node\n")
|
||||
write(hidraw, "dev", "$MAJOR:$SC2015_MINOR\n")
|
||||
link(File(dir(hidraw), "subsystem"), "/sys/class/hidraw")
|
||||
link(File(dir(hidraw), "device"), hid)
|
||||
padNodes[SC2015_MINOR] = hidraw
|
||||
link(File(LinuxRuntime.liveDir(context), "drm/sys/$MAJOR:$SC2015_MINOR"), hidraw)
|
||||
File(udevData, "c$MAJOR:$SC2015_MINOR").writeText("I:1\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\n")
|
||||
Log.i(TAG, "steam controller: /dev/$node described as the 2015 Steam Controller (28de:1102)")
|
||||
}
|
||||
describeSteamController2015()
|
||||
describeTriton(wired = true)
|
||||
if (triton) describeTriton(wired = false)
|
||||
hidrawClassDir = hidrawClass
|
||||
sysDevicesDir = devices
|
||||
sysHidrawClassDir = hidrawClass
|
||||
sysContext = context.applicationContext
|
||||
showPad(padType)
|
||||
|
||||
Log.i(TAG, "deck pad: /dev/$NODE described as a Steam Deck controller (28de:1205)")
|
||||
|
||||
@@ -181,7 +181,7 @@ internal fun SetupPanel(
|
||||
onDismiss = { editDownloadPrefix = false },
|
||||
onSave = { a.onDownloadPrefix(it); editDownloadPrefix = false },
|
||||
)
|
||||
val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_launcher), stringResource(R.string.setup_tab_storage), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses))
|
||||
val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_launcher), stringResource(R.string.setup_tab_storage), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses), "SDL3Bridge")
|
||||
var tab by rememberSaveable { mutableStateOf(if (SetupTabs.openLauncher) LAUNCHER_TAB else 0) }
|
||||
SetupTabs.openLauncher = false
|
||||
val chipFocus = remember { List(tabs.size) { FocusRequester() } }
|
||||
@@ -460,6 +460,7 @@ internal fun SetupPanel(
|
||||
}
|
||||
}
|
||||
GLASSES_TAB -> GlassesSetupPanel()
|
||||
GLASSES_TAB + 1 -> SdlBridgeSettingsTab(host) // sdl3bridge: SDL3Bridge tab
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,385 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.ServiceConnection
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.IBinder
|
||||
import android.os.Looper
|
||||
import android.os.Message
|
||||
import android.os.Messenger
|
||||
import android.os.RemoteException
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
// sdl3bridge: SDL3Bridge settings tab
|
||||
/**
|
||||
* DroidDeck's link to the SDL3 bridge app's settings. A connection of its own (not DualSenseBridge's): it never
|
||||
* registers for controller frames, it only asks for the settings state (MSG_SETTINGS_GET, once a second while
|
||||
* the tab is open) and sends single changes (MSG_SETTINGS_SET); the bridge answers both with MSG_SETTINGS.
|
||||
* The bridge sends the choices too (mode names, button names, ...), so nothing here has to match its lists.
|
||||
*/
|
||||
internal object SdlBridgeLink {
|
||||
private const val ACTION = "com.example.dsedge.BRIDGE"
|
||||
private const val SCREEN = "com.example.dsedge.BridgeActivity"
|
||||
// the bridge built into this app (SDL3DroidDeck), else the separate SDL3Bridge app
|
||||
private fun pkg(ctx: Context) = com.droiddeck.launcher.input.DualSenseBridge.bridgePackage(ctx)
|
||||
private const val MSG_SETTINGS_GET = 40
|
||||
private const val MSG_SETTINGS_SET = 41
|
||||
private const val MSG_SETTINGS = 42
|
||||
|
||||
var snapshot by mutableStateOf<Bundle?>(null)
|
||||
private set
|
||||
private var server: Messenger? = null
|
||||
private var bound = false
|
||||
private var users = 0
|
||||
|
||||
private val inbox = Messenger(object : Handler(Looper.getMainLooper()) {
|
||||
override fun handleMessage(m: Message) {
|
||||
if (m.what == MSG_SETTINGS) snapshot = Bundle(m.data)
|
||||
}
|
||||
})
|
||||
|
||||
private val conn = object : ServiceConnection {
|
||||
override fun onServiceConnected(n: ComponentName, b: IBinder) {
|
||||
server = Messenger(b)
|
||||
refresh()
|
||||
}
|
||||
override fun onServiceDisconnected(n: ComponentName) { server = null }
|
||||
}
|
||||
|
||||
fun installed(ctx: Context): Boolean = try { ctx.packageManager.getPackageInfo(pkg(ctx), 0); true } catch (_: Exception) { false }
|
||||
|
||||
fun start(ctx: Context) {
|
||||
users++
|
||||
if (bound) return
|
||||
bound = try {
|
||||
ctx.applicationContext.bindService(Intent(ACTION).setPackage(pkg(ctx)), conn, Context.BIND_AUTO_CREATE)
|
||||
} catch (_: Exception) { false }
|
||||
}
|
||||
|
||||
fun stop(ctx: Context) {
|
||||
users = maxOf(0, users - 1)
|
||||
if (users > 0 || !bound) return
|
||||
try { ctx.applicationContext.unbindService(conn) } catch (_: Exception) {}
|
||||
bound = false
|
||||
server = null
|
||||
}
|
||||
|
||||
fun connected(): Boolean = server != null
|
||||
|
||||
fun refresh() = send(Message.obtain(null, MSG_SETTINGS_GET))
|
||||
|
||||
/** One change. Shown at once; the bridge's answer then confirms it. */
|
||||
fun set(key: String, p: Int = 0, i: Int = 0, int: Int? = null, bool: Boolean? = null) {
|
||||
snapshot?.let { old -> snapshot = Bundle(old).also { applyLocally(it, key, p, i, int, bool) } }
|
||||
send(Message.obtain(null, MSG_SETTINGS_SET).apply {
|
||||
data = Bundle().apply {
|
||||
putString("key", key); putInt("p", p); putInt("i", i)
|
||||
if (int != null) putInt("int", int)
|
||||
if (bool != null) putBoolean("bool", bool)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** The bridge's own screen (controller test, USB access, ...): in this app when built in, else SDL3Bridge. */
|
||||
fun open(ctx: Context) {
|
||||
val screen = Intent().setClassName(pkg(ctx), SCREEN).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
try { ctx.startActivity(screen) } catch (_: Exception) {
|
||||
val launch = ctx.packageManager.getLaunchIntentForPackage(pkg(ctx)) ?: return
|
||||
try { ctx.startActivity(launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } catch (_: Exception) {}
|
||||
}
|
||||
}
|
||||
|
||||
private fun send(m: Message) {
|
||||
val s = server ?: return
|
||||
m.replyTo = inbox
|
||||
try { s.send(m) } catch (_: RemoteException) { server = null }
|
||||
}
|
||||
|
||||
private fun applyLocally(b: Bundle, key: String, p: Int, i: Int, int: Int?, bool: Boolean?) {
|
||||
val remapCount = b.getStringArray("remapTargets")?.size ?: 8
|
||||
fun setInt(k: String, index: Int, v: Int) {
|
||||
val a = b.getIntArray(k)?.clone() ?: return
|
||||
if (index in a.indices) a[index] = v
|
||||
b.putIntArray(k, a)
|
||||
}
|
||||
fun setBool(k: String, index: Int, v: Boolean) {
|
||||
val a = b.getBooleanArray(k)?.clone() ?: return
|
||||
if (index in a.indices) a[index] = v
|
||||
b.putBooleanArray(k, a)
|
||||
}
|
||||
when (key) {
|
||||
"presentAs", "pollMs" -> if (int != null) b.putInt(key, int)
|
||||
"driverEnabled", "forceUsb", "bubble" -> if (bool != null) b.putBoolean(key, bool)
|
||||
"gyroMap" -> if (int != null) setInt(key, p * 3 + i, int)
|
||||
"remap" -> if (int != null) setInt(key, p * remapCount + i, int)
|
||||
"calibrate" -> b.putInt("calibrating", p)
|
||||
"resetCalibration" -> b.getFloatArray("gyroBias")?.clone()?.let { a ->
|
||||
for (k in 0 until 3) if (p * 3 + k in a.indices) a[p * 3 + k] = 0f
|
||||
b.putFloatArray("gyroBias", a)
|
||||
}
|
||||
else -> {
|
||||
if (int != null) setInt(key, p, int)
|
||||
if (bool != null) setBool(key, p, bool)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The SDL3Bridge settings page: a tab of DroidDeck's Setup screen, and a page of the in-session drawer.
|
||||
* [track] gives each control the drawer's focus tracking (controller navigation); Setup passes nothing.
|
||||
*/
|
||||
@Composable
|
||||
internal fun SdlBridgeSettingsTab(host: MenuHost, track: (String) -> Modifier = { Modifier }) {
|
||||
val ctx = LocalContext.current
|
||||
val installed = remember { SdlBridgeLink.installed(ctx) }
|
||||
if (!installed) {
|
||||
SettingsGroup("SDL3Bridge") {
|
||||
SettingsRow("SDL3Bridge is not installed",
|
||||
"Install the SDL3Bridge app to use any SDL3-supported controller with DroidDeck: USB or Bluetooth, " +
|
||||
"re-presented as a Steam Deck / Sony / Steam Controller pad, or handed to Steam as itself.") {}
|
||||
}
|
||||
return
|
||||
}
|
||||
var waited by remember { mutableIntStateOf(0) }
|
||||
DisposableEffect(Unit) {
|
||||
SdlBridgeLink.start(ctx)
|
||||
onDispose { SdlBridgeLink.stop(ctx) }
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
while (true) {
|
||||
SdlBridgeLink.refresh()
|
||||
delay(1000)
|
||||
waited++
|
||||
}
|
||||
}
|
||||
val s = SdlBridgeLink.snapshot
|
||||
|
||||
var sessionEnabled by remember { mutableStateOf(com.droiddeck.launcher.session.SessionPrefs.sdl3Controllers(ctx)) }
|
||||
SettingsGroup("Session integration") {
|
||||
ToggleRow(host, "sdl3-session", "Use SDL3 controllers in sessions",
|
||||
"Enable USB controller input, controller presentation and Steam Native Hook-up for the next session.",
|
||||
sessionEnabled, chipModifier = track("sdl3-session")) {
|
||||
sessionEnabled = it
|
||||
com.droiddeck.launcher.session.SessionPrefs.setSdl3Controllers(ctx, it)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- status ----------------
|
||||
SettingsGroup("SDL3Bridge") {
|
||||
if (s == null) {
|
||||
SettingsRow(if (SdlBridgeLink.connected()) "Waiting for SDL3Bridge…" else "Connecting to SDL3Bridge…",
|
||||
if (waited >= 3) "No answer yet. Update SDL3Bridge (this tab needs a recent build), or open it once." else null) {}
|
||||
} else {
|
||||
SettingsRow("Status", s.getString("status") ?: "") {}
|
||||
val engineError = s.getString("engineError") ?: ""
|
||||
val engineMode = s.getString("engineMode") ?: ""
|
||||
if (engineError.isNotEmpty()) SettingsRow("SDL3 is not running", engineError) {}
|
||||
else if (engineMode.isNotEmpty() && engineMode != "background service") SettingsRow("SDL3 runs in", engineMode) {}
|
||||
if (!s.getBoolean("notifications", true)) SettingsRow("Status bar icon is hidden",
|
||||
"SDL3Bridge may not show notifications: open it once and tap Allow (or allow it in Android's app settings).") {}
|
||||
val padNames = s.getStringArray("padNames") ?: emptyArray()
|
||||
val padIds = s.getStringArray("padIds") ?: emptyArray()
|
||||
val battery = s.getIntArray("padBattery") ?: IntArray(0)
|
||||
val hookNames = s.getStringArray("hookNames") ?: emptyArray()
|
||||
val hookIds = s.getStringArray("hookIds") ?: emptyArray()
|
||||
val triton = s.getString("triton") ?: ""
|
||||
var any = false
|
||||
padNames.forEachIndexed { i, name ->
|
||||
if (name.isEmpty()) return@forEachIndexed
|
||||
any = true
|
||||
val bat = battery.getOrElse(i) { -1 }
|
||||
SettingsRow("Player ${i + 1}: $name",
|
||||
listOfNotNull(padIds.getOrNull(i), if (bat >= 0) "battery $bat%" else null).joinToString(" · ")) {}
|
||||
}
|
||||
hookNames.forEachIndexed { i, name ->
|
||||
if (name.isEmpty()) return@forEachIndexed
|
||||
any = true
|
||||
SettingsRow("Handed to Steam: $name",
|
||||
listOfNotNull(hookIds.getOrNull(i), "/dev/hidraw${24 + i}",
|
||||
if (s.getBoolean("fastPath")) "fast path" else null).joinToString(" · ")) {}
|
||||
}
|
||||
if (triton.isNotEmpty()) {
|
||||
any = true
|
||||
SettingsRow("Steam Controller (2026)", "$triton · raw passthrough") {}
|
||||
}
|
||||
if (!any) SettingsRow("No controller", "Plug a controller in with USB-C, or pair it over Bluetooth.") {}
|
||||
}
|
||||
ActionRow("Open SDL3Bridge", "Controller test screen, USB access, USB audio and everything else.", "Open",
|
||||
onClick = { SdlBridgeLink.open(ctx) }, modifier = track("sdl3-open"))
|
||||
}
|
||||
if (s == null) return
|
||||
|
||||
val ints = { k: String -> s.getIntArray(k) ?: IntArray(0) }
|
||||
val bools = { k: String -> s.getBooleanArray(k) ?: BooleanArray(0) }
|
||||
val names = { k: String -> s.getStringArray(k) ?: emptyArray() }
|
||||
fun indexed(k: String) = names(k).mapIndexed { i, n -> i to n }
|
||||
|
||||
// ---------------- global ----------------
|
||||
SettingsGroup("Controller mode") {
|
||||
BridgeChoiceRow(host, "sdl3-present", "Present controller as",
|
||||
"How Steam sees the controller, in the Steam session and on the desktop. Steam Native Hook-up hands USB " +
|
||||
"controllers to Steam as themselves, like on a PC (on the desktop: while Steam runs; other programs " +
|
||||
"there see an Xbox 360 controller).",
|
||||
indexed("presentNames"), s.getInt("presentAs"), chipModifier = track("sdl3-present")) { SdlBridgeLink.set("presentAs", int = it) }
|
||||
ToggleRow(host, "sdl3-driver", "SDL3 driver",
|
||||
"On: SDL3 reads the controller (all its features). Off: the controller goes back to Android and DroidDeck.",
|
||||
s.getBoolean("driverEnabled"), chipModifier = track("sdl3-driver")) { SdlBridgeLink.set("driverEnabled", bool = it) }
|
||||
if (s.getBoolean("embedded")) SettingsRow("Bluetooth and built-in controllers",
|
||||
"Handled by DroidDeck's Android input. SDL3 handles USB controllers.") {}
|
||||
else BridgeChoiceRow(host, "sdl3-source", "Controller source", "Which controllers SDL3 uses.",
|
||||
listOf(false to "USB + Bluetooth (auto)", true to "USB only (forced)"), s.getBoolean("forceUsb"), chipModifier = track("sdl3-source")) {
|
||||
SdlBridgeLink.set("forceUsb", bool = it)
|
||||
}
|
||||
val rateMs = ints("rateMs")
|
||||
BridgeChoiceRow(host, "sdl3-rate", "Poll rate", "Higher = lower gyro and trackpad latency, a little more battery. In Steam Native Hook-up it is also how often Steam gets the newest report (lower if games lag).",
|
||||
names("rateNames").mapIndexed { i, n -> rateMs.getOrElse(i) { 2 } to n }, s.getInt("pollMs"), chipModifier = track("sdl3-rate")) {
|
||||
SdlBridgeLink.set("pollMs", int = it)
|
||||
}
|
||||
val overlay = s.getBoolean("overlayAllowed")
|
||||
ToggleRow(host, "sdl3-bubble", "Floating bubble",
|
||||
if (overlay) "Tap: SDL3 driver on/off. Double tap: Steam Native Hook-up. Hold 3 s: open SDL3Bridge."
|
||||
else "Needs SDL3Bridge's \"Draw over other apps\" permission: turn the bubble on once in SDL3Bridge.",
|
||||
s.getBoolean("bubble"), enabled = overlay || s.getBoolean("bubble"), chipModifier = track("sdl3-bubble")) { SdlBridgeLink.set("bubble", bool = it) }
|
||||
}
|
||||
|
||||
// ---------------- per player ----------------
|
||||
var player by rememberSaveable { mutableIntStateOf(0) }
|
||||
val p = player
|
||||
Box(Modifier.fillMaxWidth().padding(top = 16.dp)) {
|
||||
SegmentedTabs((0 until 4).map { it to "P${it + 1}" }, player, tabModifier = { track("sdl3-player-$it") }) { player = it }
|
||||
}
|
||||
|
||||
SettingsGroup("Gyro · player ${p + 1}") {
|
||||
SliderRow("Gyro speed", "100 % = 1:1", ints("gyroGain").getOrElse(p) { 100 }, 5..800, step = 5,
|
||||
format = { "$it %" }, modifier = track("sdl3-gyrospeed-$p")) { SdlBridgeLink.set("gyroGain", p, int = it) }
|
||||
BridgeChoiceRow(host, "sdl3-gyroinv-$p", "Invert gyro axes", null, indexed("gyroInvNames"),
|
||||
ints("gyroInvert").getOrElse(p) { 0 }, chipModifier = track("sdl3-gyroinv-$p")) { SdlBridgeLink.set("gyroInvert", p, int = it) }
|
||||
for (i in 0 until 3) {
|
||||
BridgeChoiceRow(host, "sdl3-gyromap-$p-$i", "DroidDeck gyro ${"XYZ"[i]} comes from", null, indexed("axisNames"),
|
||||
ints("gyroMap").getOrElse(p * 3 + i) { i }, chipModifier = track("sdl3-gyromap-$p-$i")) { SdlBridgeLink.set("gyroMap", p, i, int = it) }
|
||||
}
|
||||
ToggleRow(host, "sdl3-accel-$p", "Accelerometer follows the axis remap",
|
||||
"Keeps gravity consistent with rotation.", bools("accelFollows").getOrElse(p) { true }, chipModifier = track("sdl3-accel-$p")) {
|
||||
SdlBridgeLink.set("accelFollows", p, bool = it)
|
||||
}
|
||||
SliderRow("Gyro deadzone", "Motion slower than this is ignored, so the view doesn't drift while you hold still.",
|
||||
ints("gyroDeadzone").getOrElse(p) { 0 }, 0..50, format = { "$it °/s" }, modifier = track("sdl3-gyrodeadzone-$p")) { SdlBridgeLink.set("gyroDeadzone", p, int = it) }
|
||||
val bias = s.getFloatArray("gyroBias") ?: FloatArray(0)
|
||||
val calibrating = s.getInt("calibrating", -1) == p
|
||||
val b = (0 until 3).map { bias.getOrElse(p * 3 + it) { 0f } }
|
||||
ActionRow("Calibrate gyro",
|
||||
when {
|
||||
calibrating -> "Hold player ${p + 1}'s controller flat and still…"
|
||||
b.all { it == 0f } -> "Lay the controller flat and still, then tap. Not calibrated yet."
|
||||
else -> "Drift removed: x %.2f, y %.2f, z %.2f °/s".format(b[0], b[1], b[2])
|
||||
}, "Calibrate", onClick = { SdlBridgeLink.set("calibrate", p) },
|
||||
modifier = track("sdl3-calibrate-$p"))
|
||||
ActionRow("Reset calibration", null, "Reset", onClick = { SdlBridgeLink.set("resetCalibration", p) },
|
||||
modifier = track("sdl3-uncalibrate-$p"))
|
||||
}
|
||||
|
||||
SettingsGroup("Touchpad · player ${p + 1}") {
|
||||
BridgeChoiceRow(host, "sdl3-touch-$p", "Layout", "How the controller's touchpad maps to the Deck's two trackpads.",
|
||||
indexed("touchNames"), ints("touchMode").getOrElse(p) { 0 }, chipModifier = track("sdl3-touch-$p")) {
|
||||
SdlBridgeLink.set("touchMode", p, int = it)
|
||||
}
|
||||
ToggleRow(host, "sdl3-tinvx-$p", "Invert X", null, bools("touchInvX").getOrElse(p) { false }, chipModifier = track("sdl3-tinvx-$p")) { SdlBridgeLink.set("touchInvX", p, bool = it) }
|
||||
ToggleRow(host, "sdl3-tinvy-$p", "Invert Y", null, bools("touchInvY").getOrElse(p) { false }, chipModifier = track("sdl3-tinvy-$p")) { SdlBridgeLink.set("touchInvY", p, bool = it) }
|
||||
ToggleRow(host, "sdl3-tswap-$p", "Swap X and Y", "Applied before inverting.", bools("touchSwap").getOrElse(p) { false }, chipModifier = track("sdl3-tswap-$p")) {
|
||||
SdlBridgeLink.set("touchSwap", p, bool = it)
|
||||
}
|
||||
}
|
||||
|
||||
SettingsGroup("Button remap · player ${p + 1}") {
|
||||
val targets = names("remapTargets")
|
||||
val remap = ints("remap")
|
||||
val sources = indexed("srcNames")
|
||||
targets.forEachIndexed { i, target ->
|
||||
BridgeChoiceRow(host, "sdl3-remap-$p-$i", target, "Pressed by", sources, remap.getOrElse(p * targets.size + i) { 0 }, chipModifier = track("sdl3-remap-$p-$i")) {
|
||||
SdlBridgeLink.set("remap", p, i, int = it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SettingsGroup("Lightbar · player ${p + 1}") {
|
||||
SliderRow("Red", null, ints("lightR").getOrElse(p) { 0 }, 0..255, modifier = track("sdl3-red-$p")) { SdlBridgeLink.set("lightR", p, int = it) }
|
||||
SliderRow("Green", null, ints("lightG").getOrElse(p) { 0 }, 0..255, modifier = track("sdl3-green-$p")) { SdlBridgeLink.set("lightG", p, int = it) }
|
||||
SliderRow("Blue", null, ints("lightB").getOrElse(p) { 255 }, 0..255, modifier = track("sdl3-blue-$p")) { SdlBridgeLink.set("lightB", p, int = it) }
|
||||
SliderRow("Brightness", null, ints("brightness").getOrElse(p) { 100 }, 0..100, format = { "$it %" }, modifier = track("sdl3-brightness-$p")) {
|
||||
SdlBridgeLink.set("brightness", p, int = it)
|
||||
}
|
||||
BridgeChoiceRow(host, "sdl3-pled-$p", "Player LEDs", null, indexed("playerLedNames"), ints("playerLed").getOrElse(p) { 0 }, chipModifier = track("sdl3-pled-$p")) {
|
||||
SdlBridgeLink.set("playerLed", p, int = it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** "Steam Native Hook-up (Steam sees the real controller)" -> "Steam Native Hook-up" + "Steam sees the real controller";
|
||||
* "Split (decoupled): left half = ..." -> "Split (decoupled)" + "left half = ...". */
|
||||
private fun splitName(name: String): Pair<String, String?> {
|
||||
val colon = name.indexOf(": ")
|
||||
if (colon > 0) return name.substring(0, colon) to name.substring(colon + 2)
|
||||
val paren = name.indexOf(" (")
|
||||
if (paren > 0 && name.endsWith(")")) return name.substring(0, paren) to name.substring(paren + 2, name.length - 1)
|
||||
return name to null
|
||||
}
|
||||
|
||||
/**
|
||||
* DroidDeck's ChoiceRow, for the bridge's (long) names. The chip shows the short name and the menu the short name
|
||||
* with the rest under it. When the chip would squeeze the label -- the session drawer is narrow, and a long chip
|
||||
* left the label no width at all, so the rows looked empty -- the chip goes under the label instead of beside it.
|
||||
*/
|
||||
@Composable
|
||||
private fun <T> BridgeChoiceRow(
|
||||
host: MenuHost, key: String, label: String, hint: String?,
|
||||
options: List<Pair<T, String>>, selected: T, chipModifier: Modifier = Modifier,
|
||||
onPick: (T) -> Unit,
|
||||
) {
|
||||
val open = host.open == key
|
||||
val parts = remember(options) { options.map { (value, name) -> splitName(name).let { Triple(value, it.first, it.second) } } }
|
||||
val chip = parts.firstOrNull { it.first == selected }?.second ?: "-"
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
// ~7 dp per character of the chip's 13 sp text, plus its padding and caret; beside the label only while
|
||||
// the label keeps at least half of the row
|
||||
val chipWidth = (parts.maxOfOrNull { it.second.length } ?: 0) * 7f + 40f
|
||||
val stacked = chipWidth > maxWidth.value * 0.5f
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
SettingsRow(label, hint, highlighted = open, stacked = stacked) {
|
||||
Box {
|
||||
ValueChip(chip, open, modifier = chipModifier.testTag("setting-$key")) { host.open = if (open) null else key }
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label) { firstItemFocus ->
|
||||
parts.forEachIndexed { index, (value, text, detail) ->
|
||||
MenuItem(text, checked = value == selected, detail = detail,
|
||||
focusRequester = if (index == 0) firstItemFocus else null) {
|
||||
onPick(value)
|
||||
host.open = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ internal enum class SessionDrawerPage(val firstControl: String) {
|
||||
EFFECTS("look"),
|
||||
VR("steamvr"),
|
||||
GAMES("anisotropy"),
|
||||
SDL3BRIDGE("sdl3-open"), // sdl3bridge: SDL3Bridge page
|
||||
SESSION("suspend"),
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@ import androidx.compose.material.icons.outlined.PictureInPictureAlt
|
||||
import androidx.compose.material.icons.automirrored.outlined.ExitToApp
|
||||
import androidx.compose.material.icons.outlined.Settings
|
||||
import androidx.compose.material.icons.outlined.SportsEsports
|
||||
import androidx.compose.material.icons.outlined.Usb
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.RadioButtonDefaults
|
||||
@@ -157,6 +158,7 @@ private val SessionDrawerPage.title: Int get() = when (this) {
|
||||
SessionDrawerPage.VR -> R.string.vr_title
|
||||
SessionDrawerPage.EFFECTS -> R.string.drawer_page_effects
|
||||
SessionDrawerPage.GAMES -> R.string.game_settings_title
|
||||
SessionDrawerPage.SDL3BRIDGE -> R.string.drawer_page_sdl3bridge
|
||||
SessionDrawerPage.SESSION -> R.string.mode_session
|
||||
}
|
||||
|
||||
@@ -168,6 +170,7 @@ private val SessionDrawerPage.icon get() = when (this) {
|
||||
SessionDrawerPage.VR -> VrHeadsetIcon
|
||||
SessionDrawerPage.EFFECTS -> Icons.Outlined.AutoFixHigh
|
||||
SessionDrawerPage.GAMES -> Icons.Outlined.Layers
|
||||
SessionDrawerPage.SDL3BRIDGE -> Icons.Outlined.Usb
|
||||
SessionDrawerPage.SESSION -> Icons.Outlined.Settings
|
||||
}
|
||||
|
||||
@@ -642,6 +645,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
track = { key -> focus.track(page, key) },
|
||||
)
|
||||
}
|
||||
SessionDrawerPage.SDL3BRIDGE -> SdlBridgeSettingsTab(host) { key -> focus.track(page, key) }
|
||||
SessionDrawerPage.SESSION -> {
|
||||
if (a.isHomeApp) SettingsGroup(stringResource(R.string.drawer_android_apps)) {
|
||||
SettingsRow(stringResource(R.string.drawer_launch_app), null) {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Status bar icon: a game controller (Material "sports_esports" shape, Apache License 2.0), white on transparent. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="#FFFFFFFF"
|
||||
android:pathData="M21.58,16.09l-1.09,-7.66C20.21,6.46 18.52,5 16.53,5H7.47C5.48,5 3.79,6.46 3.51,8.43l-1.09,7.66C2.2,17.63 3.39,19 4.94,19c0.68,0 1.32,-0.27 1.8,-0.75L9,16h6l2.25,2.25c0.48,0.48 1.13,0.75 1.8,0.75C20.61,19 21.8,17.63 21.58,16.09zM11,11H9v2H8v-2H6v-1h2V8h1v2h2V11zM15,10c-0.55,0 -1,-0.45 -1,-1s0.45,-1 1,-1 1,0.45 1,1S15.55,10 15,10zM17,13c-0.55,0 -1,-0.45 -1,-1s0.45,-1 1,-1 1,0.45 1,1S17.55,13 17,13z" />
|
||||
</vector>
|
||||
@@ -3121,4 +3121,5 @@
|
||||
<string name="stores_xbox_cloud_settings">Cloud settings</string>
|
||||
<string name="xbox_cloud_gaming" translatable="false">Xbox Cloud Gaming</string>
|
||||
<string name="xbox_filter_game_pass" translatable="false">Game Pass</string>
|
||||
<string name="drawer_page_sdl3bridge">SDL3Bridge</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- Sony (0x054C = 1356): any PlayStation controller opens this app when plugged in -->
|
||||
<usb-device vendor-id="1356" />
|
||||
<!-- Valve (0x28DE = 10462): Steam Controller (2026) cable 0x1302 = 4866, wireless puck 0x1304 / 0x1305 -->
|
||||
<usb-device vendor-id="10462" product-id="4866" />
|
||||
<usb-device vendor-id="10462" product-id="4868" />
|
||||
<usb-device vendor-id="10462" product-id="4869" />
|
||||
</resources>
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.ContextWrapper
|
||||
import android.os.Bundle
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import org.junit.After
|
||||
import org.junit.Assert.*
|
||||
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,
|
||||
instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter"],
|
||||
shadows = [JoyConPadTest.RecordingWriter::class])
|
||||
class SdlBridgeLifecycleTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
private val dirs = mutableListOf<File>()
|
||||
private val pads = mutableListOf<PadBridge>()
|
||||
|
||||
private fun pad() = PadBridge(Files.createTempDirectory("sdl-pad").toFile().also { dirs += it })
|
||||
.also { pads += it }
|
||||
|
||||
private fun attach(pad: PadBridge): ContextWrapper {
|
||||
SessionPrefs.setSdl3Controllers(app, true)
|
||||
return ContextWrapper(app).also { DualSenseBridge.attach(it, pad) }
|
||||
}
|
||||
|
||||
private fun frame(slot: Int, mask: Int = 1) {
|
||||
DualSenseBridge::class.java.getDeclaredMethod("onFrame", Bundle::class.java)
|
||||
.apply { isAccessible = true }.invoke(DualSenseBridge, Bundle().apply {
|
||||
putInt("slot", slot); putInt("mask", mask); putInt("lx", 16000)
|
||||
})
|
||||
}
|
||||
|
||||
@After fun close() {
|
||||
val token = Any()
|
||||
DualSenseBridge.beginSession(token)
|
||||
DualSenseBridge.endSession(token)
|
||||
pads.forEach { it.stop() }
|
||||
dirs.forEach { it.deleteRecursively() }
|
||||
JoyConPadTest.RecordingWriter.pads.clear()
|
||||
}
|
||||
|
||||
@Test fun replacingTheScreenReclaimsExtraPlayersAndResendsHeldInput() {
|
||||
val first = pad()
|
||||
attach(first)
|
||||
frame(0); frame(1); frame(2)
|
||||
assertTrue(JoyConPadTest.RecordingWriter.pads.getValue(1).isDown(PadState.A))
|
||||
attach(pad())
|
||||
JoyConPadTest.RecordingWriter.pads.clear()
|
||||
frame(0); frame(1); frame(2)
|
||||
for (slot in 0..2) {
|
||||
assertTrue("player $slot lost a held button", JoyConPadTest.RecordingWriter.pads.getValue(slot).isDown(PadState.A))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun anOldServiceCannotDisconnectANewerSession() {
|
||||
val old = Any()
|
||||
val current = Any()
|
||||
DualSenseBridge.beginSession(old)
|
||||
attach(pad())
|
||||
DualSenseBridge.beginSession(current)
|
||||
attach(pad())
|
||||
DualSenseBridge.endSession(old)
|
||||
frame(1)
|
||||
assertTrue(JoyConPadTest.RecordingWriter.pads.getValue(1).isDown(PadState.A))
|
||||
DualSenseBridge.endSession(current)
|
||||
JoyConPadTest.RecordingWriter.pads.clear()
|
||||
frame(1)
|
||||
assertTrue(JoyConPadTest.RecordingWriter.pads.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aCanceledLaunchCanDisconnectItsScreenWithoutAService() {
|
||||
val screen = attach(pad())
|
||||
DualSenseBridge.detach(screen)
|
||||
frame(1)
|
||||
assertFalse(DualSenseBridge.isBridgedSlot(1))
|
||||
assertFalse(DualSenseBridge::class.java.getDeclaredField("sessionActive")
|
||||
.apply { isAccessible = true }.getBoolean(DualSenseBridge))
|
||||
}
|
||||
|
||||
@Test fun anOldScreenCannotDisconnectItsReplacement() {
|
||||
val old = attach(pad())
|
||||
attach(pad())
|
||||
DualSenseBridge.detach(old)
|
||||
DualSenseBridge.screenClosed(old)
|
||||
frame(1)
|
||||
assertTrue(JoyConPadTest.RecordingWriter.pads.getValue(1).isDown(PadState.A))
|
||||
}
|
||||
|
||||
@Test fun attachingTheSamePadPreservesItsPlayerClaims() {
|
||||
val current = pad()
|
||||
attach(current)
|
||||
frame(1)
|
||||
attach(current)
|
||||
assertEquals(2, current.claimBridgeSlot())
|
||||
}
|
||||
|
||||
@Test fun sessionIntegrationRequiresExplicitOptIn() {
|
||||
SessionPrefs.setSdl3Controllers(app, false)
|
||||
assertFalse(HookupBridge.wanted(app))
|
||||
assertFalse(DualSenseBridge.attach(app, pad()))
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,16 @@ class RumbleComponentTest {
|
||||
|
||||
@After fun stopListener() { rumble.stop() }
|
||||
|
||||
@Test fun switchingToTheBridgeCancelsLocalMotorsAndTheirKeepalive() {
|
||||
effect(ms = 65535)
|
||||
assertTrue(shadowOf(vibrator).isVibrating)
|
||||
rumble.bridgeRumble = { _, _, _, _ -> true }
|
||||
effect(ms = 65535)
|
||||
assertFalse(shadowOf(vibrator).isVibrating)
|
||||
idle(2000)
|
||||
assertFalse("the old keepalive restarted local rumble", shadowOf(vibrator).isVibrating)
|
||||
}
|
||||
|
||||
@Test fun disablingCancelsCurrentEffectAndDropsSubsequentEffectsUntilEnabled() {
|
||||
effect()
|
||||
assertTrue(shadowOf(vibrator).isVibrating)
|
||||
|
||||
@@ -22,7 +22,8 @@ class SessionDrawerPageTest {
|
||||
assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.DISPLAY, 1))
|
||||
assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1))
|
||||
assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.VR, 1))
|
||||
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1))
|
||||
assertEquals(SessionDrawerPage.SDL3BRIDGE, pages.step(SessionDrawerPage.GAMES, 1))
|
||||
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.SDL3BRIDGE, 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.example.dsedge
|
||||
|
||||
import android.app.Application
|
||||
import android.content.ComponentName
|
||||
import android.content.ContextWrapper
|
||||
import android.content.pm.PackageManager
|
||||
import android.view.KeyEvent
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.SeekBar
|
||||
import java.lang.reflect.Proxy
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.Before
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], application = Application::class)
|
||||
class EmbeddedBridgeTest {
|
||||
@Before fun resetSettings() {
|
||||
Settings::class.java.getDeclaredField("prefs").apply { isAccessible = true }.set(null, null)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keyboardSliderChangesAreSavedWithoutATouchDrag() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
Settings.init(app)
|
||||
val activity = Robolectric.buildActivity(BridgeActivity::class.java).get()
|
||||
val root = LinearLayout(activity)
|
||||
val sinkType = BridgeActivity::class.java.declaredClasses.single { it.simpleName == "IntSink" }
|
||||
val sink = Proxy.newProxyInstance(sinkType.classLoader, arrayOf(sinkType)) { _, method, args ->
|
||||
if (method.name == "set") Settings.gyroGain[1] = args[0] as Int
|
||||
null
|
||||
}
|
||||
Settings.gyroGain[1] = 100
|
||||
BridgeActivity::class.java.declaredMethods.single { it.name == "addSlider" }
|
||||
.apply { isAccessible = true }.invoke(activity, root, "Gyro speed", 800, 100, sink)
|
||||
val slider = root.getChildAt(1) as SeekBar
|
||||
assertTrue(slider.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT,
|
||||
KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT)))
|
||||
assertTrue(slider.progress > 100)
|
||||
assertEquals(slider.progress, app.getSharedPreferences(Host.prefs(app, "bridge"), 0)
|
||||
.getInt("gyroGain_p1", -1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun calibrationUsesOnlyTheSelectedPlayer() {
|
||||
Settings.init(RuntimeEnvironment.getApplication())
|
||||
val activity = Robolectric.buildActivity(BridgeActivity::class.java).get()
|
||||
fun field(name: String) = BridgeActivity::class.java.getDeclaredField(name).apply { isAccessible = true }
|
||||
field("calibPlayer").setInt(activity, 2)
|
||||
field("calibCount").setInt(activity, 0)
|
||||
val frame = FloatArray(13).apply { this[7] = 0.5f; this[8] = -1f; this[9] = 2f }
|
||||
activity.onFrame(frame, 1)
|
||||
assertEquals(0, field("calibCount").getInt(activity))
|
||||
repeat(180) { activity.onFrame(frame, 2) }
|
||||
assertEquals(-1, field("calibCount").getInt(activity))
|
||||
assertEquals(28.64789f, Settings.gyroBias[2][0], 0.0001f)
|
||||
assertEquals(-57.29578f, Settings.gyroBias[2][1], 0.0001f)
|
||||
assertEquals(114.59156f, Settings.gyroBias[2][2], 0.0001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun driverComponentsStayPrivateAndRunOutsideTheSessionProcess() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val pm = app.packageManager
|
||||
val service = pm.getServiceInfo(ComponentName(app, "com.example.dsedge.BridgeService"), 0)
|
||||
assertFalse(service.exported)
|
||||
assertEquals("${app.packageName}:sdl3", service.processName)
|
||||
for (name in listOf("BridgeActivity", "SdlHostActivity")) {
|
||||
val activity = pm.getActivityInfo(ComponentName(app, "com.example.dsedge.$name"), 0)
|
||||
assertFalse(activity.exported)
|
||||
assertEquals(service.processName, activity.processName)
|
||||
}
|
||||
val usb = pm.getActivityInfo(ComponentName(app, "com.example.dsedge.UsbAttachActivity"),
|
||||
PackageManager.GET_META_DATA)
|
||||
assertTrue(usb.exported)
|
||||
assertEquals(service.processName, usb.processName)
|
||||
assertTrue(usb.metaData.containsKey("android.hardware.usb.action.USB_DEVICE_ATTACHED"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun embeddedBridgePreferencesDoNotShareDroidDeckSettings() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
assertTrue(Host.embedded(app))
|
||||
assertEquals("sdl3bridge_settings", Host.prefs(app, "settings"))
|
||||
assertEquals("sdl3bridge_engine", Host.prefs(app, "engine"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun headlessEmbeddedDriverLeavesAndroidControllersToDroidDeck() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
assertTrue(Host.usbOnly(app, false))
|
||||
assertTrue(Host.usbOnly(app, true))
|
||||
val standalone = object : ContextWrapper(app) {
|
||||
override fun getPackageName() = Host.OWN_PACKAGE
|
||||
}
|
||||
assertFalse(Host.usbOnly(standalone, false))
|
||||
assertTrue(Host.usbOnly(standalone, true))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
# SDL3 controller bridge
|
||||
|
||||
The integrated bridge runs in DroidDeck's `:sdl3` process. Open **Setup → SDL3Bridge**
|
||||
or the SDL3Bridge page in the session drawer to configure up to four controllers.
|
||||
Enable **Use SDL3 controllers in sessions** before starting a session. This opt-in
|
||||
also enables SDL3 controller presentation on the desktop and Steam Native Hook-up.
|
||||
USB controllers use SDL3's HID drivers; Android input remains the fallback for
|
||||
Bluetooth and built-in controllers. The embedded driver only claims USB controllers:
|
||||
Android events are delivered to DroidDeck's activity and cannot reach the separate
|
||||
headless SDL process. Steam Native Hook-up forwards a USB controller's
|
||||
identity and reports to Steam so Steam can use its own controller driver.
|
||||
|
||||
USB access requires Android's device permission. The optional floating control also
|
||||
requires permission to display over other apps. A separate SDL3Bridge installation
|
||||
should be stopped before using the integrated bridge with the same USB controller.
|
||||
Gyro, touchpad, remapping and lightbar settings belong to Steam while Hook-up is active.
|
||||
|
||||
## Source and attribution
|
||||
|
||||
The controller implementation is by [pablo89898991](https://github.com/pablo89898991),
|
||||
imported from [SdlBridge at 63feeac6](https://github.com/pablo89898991/SdlBridge/tree/63feeac6a3b9f3b51ec7664d677e099cdf5ae4d0)
|
||||
through [SDLApiDroidDeck at 131f1cef](https://github.com/pablo89898991/SDLApiDroidDeck/tree/131f1ceffe52554758079c6a3bb3c045b9be2afe).
|
||||
The imported commit retains Pablo's Git author identity. DroidDeck integration and
|
||||
build adjustments are recorded separately.
|
||||
|
||||
Reusable bridge code and SDL's Android Java bindings are unchanged snapshots under
|
||||
`third_party/sdlbridge` and `third_party/sdl3`. Their manifests pin upstream revisions
|
||||
and every source file's hash. Small patches hold the embedded-mode changes. Gradle
|
||||
verifies and prepares the patched sources under `app/build/controller-sources` before
|
||||
Java or native compilation. See [the update procedure](../../third_party/README.md).
|
||||
|
||||
The port keeps DroidDeck's name, signing, workflows and test failure handling. It
|
||||
excludes the fork's ADPF changes, cursor-compositing default, Steam controller-rate
|
||||
override, and CI/download fallbacks.
|
||||
|
||||
SDL 3.4.18 is downloaded by CMake from its official release archive and verified
|
||||
against its SHA-256 digest. Its Android Java classes are imported from the same
|
||||
release. The separate SDL Java patch leaves Bluetooth handling with DroidDeck.
|
||||
SDL uses the zlib license, included in
|
||||
`app/src/main/assets/licenses/sdl3/LICENSE.txt`; the bridge is distributed under
|
||||
DroidDeck's GPLv3 license.
|
||||
|
||||
## Hardware checks
|
||||
|
||||
Check that the built-in controller still navigates DroidDeck and Steam with the
|
||||
SDL3 driver both enabled and disabled. Open the bridge settings and controller test
|
||||
screen, then start and stop a session without a USB controller attached.
|
||||
|
||||
With a USB controller, grant access and verify hot-plug, buttons, sticks, gyro,
|
||||
touchpad and rumble in presented-controller mode. Repeat with Steam Native Hook-up,
|
||||
including switching back, disconnecting, and reconnecting. Verify multiple player
|
||||
slots and Steam on the desktop when the corresponding hardware is available.
|
||||
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
# Controller source snapshots
|
||||
|
||||
`sdlbridge/upstream` contains the reusable Java and native controller implementation
|
||||
by pablo89898991. `sdl3/upstream` contains SDL's Android Java bindings. Each snapshot's
|
||||
`upstream.json` records its exact upstream revision or release archive and the
|
||||
SHA-256 of every imported file. License notices are included alongside the snapshots.
|
||||
|
||||
Keep snapshots unchanged. DroidDeck's embedded-mode adjustments live in each
|
||||
component's `patches` directory. `prepareControllerSources` verifies the snapshots
|
||||
and applies those patches into `app/build/controller-sources`; Kotlin, Java and CMake
|
||||
compile against that generated directory. No SdlBridge download is needed to build.
|
||||
SDL's native release archive is separately pinned and hash-checked by CMake.
|
||||
|
||||
DroidDeck's Compose UI, session lifecycle, controller slots and Linux input integration
|
||||
remain in the application's normal source directories.
|
||||
|
||||
To update a dependency, import the selected upstream files, update the revision and
|
||||
file hashes in `upstream.json`, and rebase the small local patch set. Run
|
||||
`python3 tools/prepare_controller_sources.py` to check the inventory, hashes and patch
|
||||
application before building. An upstream change that breaks a patch fails preparation.
|
||||
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
Copyright (C) 1997-2026 Sam Lantinga <slouken@libsdl.org>
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
3. This notice may not be removed or altered from any source distribution.
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
--- a/java/org/libsdl/app/HIDDeviceManager.java
|
||||
+++ b/java/org/libsdl/app/HIDDeviceManager.java
|
||||
@@ -377,6 +377,10 @@
|
||||
}
|
||||
|
||||
private void initializeBluetooth() {
|
||||
+ if (true) { // sdl3droiddeck: Bluetooth controllers are DroidDeck's own (SteamControllerBle)
|
||||
+ Log.d(TAG, "Bluetooth left to the app");
|
||||
+ return;
|
||||
+ }
|
||||
Log.d(TAG, "Initializing Bluetooth");
|
||||
|
||||
if (Build.VERSION.SDK_INT >= 31 /* Android 12 */ &&
|
||||
Vendored
+61
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"version": 1,
|
||||
"source": {
|
||||
"version": "3.4.18",
|
||||
"archive": "https://github.com/libsdl-org/SDL/releases/download/release-3.4.18/SDL3-3.4.18.tar.gz",
|
||||
"sha256": "9c75cf16330322c217dedd2e0609f1124f1b54b8633e763467b4684d0f4334a3"
|
||||
},
|
||||
"files": {
|
||||
"java/org/libsdl/app/HIDDevice.java": {
|
||||
"source": "android-project/app/src/main/java/org/libsdl/app/HIDDevice.java",
|
||||
"sha256": "afdeaf583f051583eff5cc9dcbfb983e3e8923e66d1130ff3e30c21afc8f87f1"
|
||||
},
|
||||
"java/org/libsdl/app/HIDDeviceBLESteamController.java": {
|
||||
"source": "android-project/app/src/main/java/org/libsdl/app/HIDDeviceBLESteamController.java",
|
||||
"sha256": "2f88711d2c5bb2114be4273b6f3461b165cf19fcedae714d0c0105b2422a4c36"
|
||||
},
|
||||
"java/org/libsdl/app/HIDDeviceManager.java": {
|
||||
"source": "android-project/app/src/main/java/org/libsdl/app/HIDDeviceManager.java",
|
||||
"sha256": "5bff9432726930a17cad9502191dd807da2e3cbcff2ad6990966b4b4bd9a7757"
|
||||
},
|
||||
"java/org/libsdl/app/HIDDeviceUSB.java": {
|
||||
"source": "android-project/app/src/main/java/org/libsdl/app/HIDDeviceUSB.java",
|
||||
"sha256": "2304ead390ae8839405f338866646fd7e12013732c5abe9339af60864626ddf4"
|
||||
},
|
||||
"java/org/libsdl/app/SDL.java": {
|
||||
"source": "android-project/app/src/main/java/org/libsdl/app/SDL.java",
|
||||
"sha256": "49d13bd76b65b40bc13b8f4ff1333ecf9fc5473a57bb2d216e2a60dc2e5973a4"
|
||||
},
|
||||
"java/org/libsdl/app/SDLActivity.java": {
|
||||
"source": "android-project/app/src/main/java/org/libsdl/app/SDLActivity.java",
|
||||
"sha256": "41e9a367d1b623d56735a2f6301dd2370ce1e43ecbb5e956ebb517202e2a200c"
|
||||
},
|
||||
"java/org/libsdl/app/SDLAudioManager.java": {
|
||||
"source": "android-project/app/src/main/java/org/libsdl/app/SDLAudioManager.java",
|
||||
"sha256": "129990250d389bc6550c1a27a81ee9a4cc32a4d6e9080f2fe466480988f214eb"
|
||||
},
|
||||
"java/org/libsdl/app/SDLControllerManager.java": {
|
||||
"source": "android-project/app/src/main/java/org/libsdl/app/SDLControllerManager.java",
|
||||
"sha256": "3bb5d739727b72688cdfe4fe2a3dd6fd7005a2fd2aac311deeda1e53c23e3981"
|
||||
},
|
||||
"java/org/libsdl/app/SDLDummyEdit.java": {
|
||||
"source": "android-project/app/src/main/java/org/libsdl/app/SDLDummyEdit.java",
|
||||
"sha256": "fb777fa4b4cce4d328229014acf156c2c2f47445dacccd5f74f876a64cdf502b"
|
||||
},
|
||||
"java/org/libsdl/app/SDLInputConnection.java": {
|
||||
"source": "android-project/app/src/main/java/org/libsdl/app/SDLInputConnection.java",
|
||||
"sha256": "7079f65944ce0f6e8e3ca0293fc79c1e4e050f3b4290c39990723e3a0e40bc9b"
|
||||
},
|
||||
"java/org/libsdl/app/SDLSensorManager.java": {
|
||||
"source": "android-project/app/src/main/java/org/libsdl/app/SDLSensorManager.java",
|
||||
"sha256": "3ffd781744c54e6809ad61515d254af366d34b44e086db90a296c8f159f13dd7"
|
||||
},
|
||||
"java/org/libsdl/app/SDLSurface.java": {
|
||||
"source": "android-project/app/src/main/java/org/libsdl/app/SDLSurface.java",
|
||||
"sha256": "94762faf8067f9ff64b96c8be13c04c1d6daa5561b59f753e9ad0c0aa30e23c8"
|
||||
}
|
||||
},
|
||||
"patches": [
|
||||
"patches/0001-droiddeck-integration.patch"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.hardware.usb.UsbDevice;
|
||||
|
||||
interface HIDDevice
|
||||
{
|
||||
public int getId();
|
||||
public int getVendorId();
|
||||
public int getProductId();
|
||||
public String getSerialNumber();
|
||||
public int getVersion();
|
||||
public String getManufacturerName();
|
||||
public String getProductName();
|
||||
public UsbDevice getDevice();
|
||||
public boolean open();
|
||||
public int writeReport(byte[] report, boolean feature);
|
||||
public boolean readReport(byte[] report, boolean feature);
|
||||
public void setFrozen(boolean frozen);
|
||||
public void close();
|
||||
public void shutdown();
|
||||
}
|
||||
+829
@@ -0,0 +1,829 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.content.Context;
|
||||
import android.bluetooth.BluetoothDevice;
|
||||
import android.bluetooth.BluetoothGatt;
|
||||
import android.bluetooth.BluetoothGattCallback;
|
||||
import android.bluetooth.BluetoothGattCharacteristic;
|
||||
import android.bluetooth.BluetoothGattDescriptor;
|
||||
import android.bluetooth.BluetoothManager;
|
||||
import android.bluetooth.BluetoothProfile;
|
||||
import android.bluetooth.BluetoothGattService;
|
||||
import android.hardware.usb.UsbDevice;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
import android.os.*;
|
||||
|
||||
//import com.android.internal.util.HexDump;
|
||||
|
||||
import java.lang.Runnable;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.UUID;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.Matcher;
|
||||
|
||||
class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDevice {
|
||||
|
||||
private static final String TAG = "hidapi";
|
||||
private HIDDeviceManager mManager;
|
||||
private BluetoothDevice mDevice;
|
||||
private int mDeviceId;
|
||||
private BluetoothGatt mGatt;
|
||||
private boolean mIsRegistered = false;
|
||||
private boolean mIsConnected = false;
|
||||
private boolean mIsChromebook = false;
|
||||
private boolean mIsReconnecting = false;
|
||||
private boolean mHasEnabledNotifications = false;
|
||||
private boolean mHasSeenInputUpdate = false;
|
||||
private boolean mFrozen = false;
|
||||
private LinkedList<GattOperation> mOperations;
|
||||
GattOperation mCurrentOperation = null;
|
||||
private Handler mHandler;
|
||||
private int mProductId = -1;
|
||||
private int mReportId = 0;
|
||||
private UUID mInputCharacteristic;
|
||||
|
||||
private static final int D0G_BLE2_PID = 0x1106;
|
||||
private static final int TRITON_BLE_PID = 0x1303;
|
||||
|
||||
|
||||
private static final int TRANSPORT_AUTO = 0;
|
||||
private static final int TRANSPORT_BREDR = 1;
|
||||
private static final int TRANSPORT_LE = 2;
|
||||
|
||||
private static final int CHROMEBOOK_CONNECTION_CHECK_INTERVAL = 10000;
|
||||
|
||||
static final UUID steamControllerService = UUID.fromString("100F6C32-1735-4313-B402-38567131E5F3");
|
||||
static final UUID inputCharacteristicD0G = UUID.fromString("100F6C33-1735-4313-B402-38567131E5F3");
|
||||
static final UUID inputCharacteristicTriton_0x45 = UUID.fromString("100F6C7A-1735-4313-B402-38567131E5F3");
|
||||
static final UUID inputCharacteristicTriton_0x47 = UUID.fromString("100F6C7C-1735-4313-B402-38567131E5F3");
|
||||
static final UUID reportCharacteristic = UUID.fromString("100F6C34-1735-4313-B402-38567131E5F3");
|
||||
static private final byte[] enterValveMode = new byte[] { (byte)0xC0, (byte)0x87, 0x03, 0x08, 0x07, 0x00 };
|
||||
|
||||
private HashMap<Integer, BluetoothGattCharacteristic> mOutputReportChars = new HashMap<Integer, BluetoothGattCharacteristic>();
|
||||
|
||||
static class GattOperation {
|
||||
private enum Operation {
|
||||
CHR_READ,
|
||||
CHR_WRITE,
|
||||
ENABLE_NOTIFICATION
|
||||
}
|
||||
|
||||
Operation mOp;
|
||||
UUID mUuid;
|
||||
byte[] mValue;
|
||||
BluetoothGatt mGatt;
|
||||
boolean mResult = true;
|
||||
int mDelayMs = 0;
|
||||
|
||||
private GattOperation(BluetoothGatt gatt, GattOperation.Operation operation, UUID uuid) {
|
||||
mGatt = gatt;
|
||||
mOp = operation;
|
||||
mUuid = uuid;
|
||||
}
|
||||
|
||||
private GattOperation(BluetoothGatt gatt, GattOperation.Operation operation, UUID uuid, int delayMs) {
|
||||
mGatt = gatt;
|
||||
mOp = operation;
|
||||
mUuid = uuid;
|
||||
mDelayMs = delayMs;
|
||||
}
|
||||
|
||||
private GattOperation(BluetoothGatt gatt, GattOperation.Operation operation, UUID uuid, byte[] value) {
|
||||
mGatt = gatt;
|
||||
mOp = operation;
|
||||
mUuid = uuid;
|
||||
mValue = value;
|
||||
}
|
||||
|
||||
private GattOperation(BluetoothGatt gatt, GattOperation.Operation operation, UUID uuid, byte[] value, int delayMs) {
|
||||
mGatt = gatt;
|
||||
mOp = operation;
|
||||
mUuid = uuid;
|
||||
mValue = value;
|
||||
mDelayMs = delayMs;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
// This is executed in main thread
|
||||
BluetoothGattCharacteristic chr;
|
||||
|
||||
switch (mOp) {
|
||||
case CHR_READ:
|
||||
chr = getCharacteristic(mUuid);
|
||||
//Log.v(TAG, "Reading characteristic " + chr.getUuid());
|
||||
if (!mGatt.readCharacteristic(chr)) {
|
||||
Log.e(TAG, "Unable to read characteristic " + mUuid.toString());
|
||||
mResult = false;
|
||||
break;
|
||||
}
|
||||
mResult = true;
|
||||
break;
|
||||
case CHR_WRITE:
|
||||
chr = getCharacteristic(mUuid);
|
||||
//Log.v(TAG, "Writing characteristic " + chr.getUuid() + " value=" + HexDump.toHexString(value));
|
||||
chr.setValue(mValue);
|
||||
if (!mGatt.writeCharacteristic(chr)) {
|
||||
Log.e(TAG, "Unable to write characteristic " + mUuid.toString());
|
||||
mResult = false;
|
||||
break;
|
||||
}
|
||||
mResult = true;
|
||||
break;
|
||||
case ENABLE_NOTIFICATION:
|
||||
chr = getCharacteristic(mUuid);
|
||||
//Log.v(TAG, "Writing descriptor of " + chr.getUuid());
|
||||
if (chr != null) {
|
||||
BluetoothGattDescriptor cccd = chr.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
|
||||
if (cccd != null) {
|
||||
int properties = chr.getProperties();
|
||||
byte[] value;
|
||||
if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) == BluetoothGattCharacteristic.PROPERTY_NOTIFY) {
|
||||
value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
|
||||
} else if ((properties & BluetoothGattCharacteristic.PROPERTY_INDICATE) == BluetoothGattCharacteristic.PROPERTY_INDICATE) {
|
||||
value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE;
|
||||
} else {
|
||||
Log.e(TAG, "Unable to start notifications on input characteristic");
|
||||
mResult = false;
|
||||
return;
|
||||
}
|
||||
|
||||
mGatt.setCharacteristicNotification(chr, true);
|
||||
cccd.setValue(value);
|
||||
if (!mGatt.writeDescriptor(cccd)) {
|
||||
Log.e(TAG, "Unable to write descriptor " + mUuid.toString());
|
||||
mResult = false;
|
||||
return;
|
||||
}
|
||||
mResult = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean finish() {
|
||||
return mResult;
|
||||
}
|
||||
|
||||
public int getDelayMs() { return mDelayMs; }
|
||||
|
||||
private BluetoothGattCharacteristic getCharacteristic(UUID uuid) {
|
||||
BluetoothGattService valveService = mGatt.getService(steamControllerService);
|
||||
if (valveService == null)
|
||||
return null;
|
||||
return valveService.getCharacteristic(uuid);
|
||||
}
|
||||
|
||||
static public GattOperation readCharacteristic(BluetoothGatt gatt, UUID uuid) {
|
||||
return new GattOperation(gatt, Operation.CHR_READ, uuid);
|
||||
}
|
||||
|
||||
static public GattOperation writeCharacteristic(BluetoothGatt gatt, UUID uuid, byte[] value) {
|
||||
return new GattOperation(gatt, Operation.CHR_WRITE, uuid, value);
|
||||
}
|
||||
|
||||
static public GattOperation enableNotification(BluetoothGatt gatt, UUID uuid) {
|
||||
return new GattOperation(gatt, Operation.ENABLE_NOTIFICATION, uuid);
|
||||
}
|
||||
|
||||
static public GattOperation enableNotification(BluetoothGatt gatt, UUID uuid, int delayMs) {
|
||||
return new GattOperation(gatt, Operation.ENABLE_NOTIFICATION, uuid, delayMs);
|
||||
}
|
||||
}
|
||||
|
||||
HIDDeviceBLESteamController(HIDDeviceManager manager, BluetoothDevice device) {
|
||||
mManager = manager;
|
||||
mDevice = device;
|
||||
mDeviceId = mManager.getDeviceIDForIdentifier(getIdentifier());
|
||||
mIsRegistered = false;
|
||||
mIsChromebook = SDLActivity.isChromebook();
|
||||
mOperations = new LinkedList<GattOperation>();
|
||||
mHandler = new Handler(Looper.getMainLooper());
|
||||
|
||||
mGatt = connectGatt();
|
||||
mHasEnabledNotifications = false;
|
||||
mHasSeenInputUpdate = false;
|
||||
// final HIDDeviceBLESteamController finalThis = this;
|
||||
// mHandler.postDelayed(new Runnable() {
|
||||
// @Override
|
||||
// void run() {
|
||||
// finalThis.checkConnectionForChromebookIssue();
|
||||
// }
|
||||
// }, CHROMEBOOK_CONNECTION_CHECK_INTERVAL);
|
||||
}
|
||||
|
||||
String getIdentifier() {
|
||||
return String.format("SteamController.%s", mDevice.getAddress());
|
||||
}
|
||||
|
||||
BluetoothGatt getGatt() {
|
||||
return mGatt;
|
||||
}
|
||||
|
||||
// Because on Chromebooks we show up as a dual-mode device, it will attempt to connect TRANSPORT_AUTO, which will use TRANSPORT_BREDR instead
|
||||
// of TRANSPORT_LE. Let's force ourselves to connect low energy.
|
||||
private BluetoothGatt connectGatt(boolean managed) {
|
||||
if (Build.VERSION.SDK_INT >= 23 /* Android 6.0 (M) */) {
|
||||
try {
|
||||
return mDevice.connectGatt(mManager.getContext(), managed, this, TRANSPORT_LE);
|
||||
} catch (Exception e) {
|
||||
return mDevice.connectGatt(mManager.getContext(), managed, this);
|
||||
}
|
||||
} else {
|
||||
return mDevice.connectGatt(mManager.getContext(), managed, this);
|
||||
}
|
||||
}
|
||||
|
||||
private BluetoothGatt connectGatt() {
|
||||
return connectGatt(false);
|
||||
}
|
||||
|
||||
protected int getConnectionState() {
|
||||
|
||||
Context context = mManager.getContext();
|
||||
if (context == null) {
|
||||
// We are lacking any context to get our Bluetooth information. We'll just assume disconnected.
|
||||
return BluetoothProfile.STATE_DISCONNECTED;
|
||||
}
|
||||
|
||||
BluetoothManager btManager = (BluetoothManager)context.getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
if (btManager == null) {
|
||||
// This device doesn't support Bluetooth. We should never be here, because how did
|
||||
// we instantiate a device to start with?
|
||||
return BluetoothProfile.STATE_DISCONNECTED;
|
||||
}
|
||||
|
||||
return btManager.getConnectionState(mDevice, BluetoothProfile.GATT);
|
||||
}
|
||||
|
||||
void reconnect() {
|
||||
|
||||
if (getConnectionState() != BluetoothProfile.STATE_CONNECTED) {
|
||||
mGatt.disconnect();
|
||||
mGatt = connectGatt();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected void checkConnectionForChromebookIssue() {
|
||||
if (!mIsChromebook) {
|
||||
// We only do this on Chromebooks, because otherwise it's really annoying to just attempt
|
||||
// over and over.
|
||||
return;
|
||||
}
|
||||
|
||||
int connectionState = getConnectionState();
|
||||
|
||||
switch (connectionState) {
|
||||
case BluetoothProfile.STATE_CONNECTED:
|
||||
if (!mIsConnected) {
|
||||
// We are in the Bad Chromebook Place. We can force a disconnect
|
||||
// to try to recover.
|
||||
Log.v(TAG, "Chromebook: We are in a very bad state; the controller shows as connected in the underlying Bluetooth layer, but we never received a callback. Forcing a reconnect.");
|
||||
mIsReconnecting = true;
|
||||
mGatt.disconnect();
|
||||
mGatt = connectGatt(false);
|
||||
break;
|
||||
}
|
||||
else if (!isRegistered()) {
|
||||
if (mGatt.getServices().size() > 0) {
|
||||
Log.v(TAG, "Chromebook: We are connected to a controller, but never got our registration. Trying to recover.");
|
||||
probeService(this);
|
||||
}
|
||||
else {
|
||||
Log.v(TAG, "Chromebook: We are connected to a controller, but never discovered services. Trying to recover.");
|
||||
mIsReconnecting = true;
|
||||
mGatt.disconnect();
|
||||
mGatt = connectGatt(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
else {
|
||||
Log.v(TAG, "Chromebook: We are connected, and registered. Everything's good!");
|
||||
return;
|
||||
}
|
||||
break;
|
||||
|
||||
case BluetoothProfile.STATE_DISCONNECTED:
|
||||
Log.v(TAG, "Chromebook: We have either been disconnected, or the Chromebook BtGatt.ContextMap bug has bitten us. Attempting a disconnect/reconnect, but we may not be able to recover.");
|
||||
|
||||
mIsReconnecting = true;
|
||||
mGatt.disconnect();
|
||||
mGatt = connectGatt(false);
|
||||
break;
|
||||
|
||||
case BluetoothProfile.STATE_CONNECTING:
|
||||
Log.v(TAG, "Chromebook: We're still trying to connect. Waiting a bit longer.");
|
||||
break;
|
||||
}
|
||||
|
||||
final HIDDeviceBLESteamController finalThis = this;
|
||||
mHandler.postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
finalThis.checkConnectionForChromebookIssue();
|
||||
}
|
||||
}, CHROMEBOOK_CONNECTION_CHECK_INTERVAL);
|
||||
}
|
||||
|
||||
private boolean isRegistered() {
|
||||
return mIsRegistered;
|
||||
}
|
||||
|
||||
private void setRegistered() {
|
||||
mIsRegistered = true;
|
||||
}
|
||||
|
||||
private boolean probeService(HIDDeviceBLESteamController controller) {
|
||||
|
||||
if (isRegistered()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!mIsConnected) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Log.v(TAG, "probeService controller=" + controller);
|
||||
|
||||
for (BluetoothGattService service : mGatt.getServices()) {
|
||||
if (service.getUuid().equals(steamControllerService)) {
|
||||
Log.v(TAG, "Found Valve steam controller service " + service.getUuid());
|
||||
|
||||
for (BluetoothGattCharacteristic chr : service.getCharacteristics()) {
|
||||
if (chr.getUuid().equals(inputCharacteristicTriton_0x45)) {
|
||||
Log.v(TAG, "Found Triton input characteristic 0x45");
|
||||
mProductId = TRITON_BLE_PID;
|
||||
mReportId = 0x45;
|
||||
mInputCharacteristic = chr.getUuid();
|
||||
} else if (chr.getUuid().equals(inputCharacteristicTriton_0x47)) {
|
||||
Log.v(TAG, "Found Triton input characteristic 0x47");
|
||||
mProductId = TRITON_BLE_PID;
|
||||
mReportId = 0x47;
|
||||
mInputCharacteristic = chr.getUuid();
|
||||
} else if (chr.getUuid().equals(inputCharacteristicD0G)) {
|
||||
Log.v(TAG, "Found D0G input characteristic");
|
||||
mProductId = D0G_BLE2_PID;
|
||||
mReportId = 0x03;
|
||||
mInputCharacteristic = chr.getUuid();
|
||||
} else {
|
||||
Pattern reportPattern = Pattern.compile("100F6C([0-9A-Z]{2})", Pattern.CASE_INSENSITIVE);
|
||||
Matcher matcher = reportPattern.matcher(chr.getUuid().toString());
|
||||
|
||||
if (matcher.find()) {
|
||||
try {
|
||||
int reportId = Integer.parseInt(matcher.group(1), 16);
|
||||
|
||||
reportId -= 0x35;
|
||||
if (reportId >= 0x80) {
|
||||
// This is a Triton output report characteristic that we need to care about.
|
||||
Log.v(TAG, "Found Triton output report 0x" + Integer.toString(reportId, 16));
|
||||
mOutputReportChars.put(reportId, chr);
|
||||
}
|
||||
}
|
||||
catch (NumberFormatException nfe) {
|
||||
Log.w(TAG, "Could not parse report characteristic " + chr.getUuid().toString() + ": " + nfe.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (BluetoothGattCharacteristic chr : service.getCharacteristics()) {
|
||||
if (chr.getUuid().equals(mInputCharacteristic)) {
|
||||
// Start notifications
|
||||
BluetoothGattDescriptor cccd = chr.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
|
||||
if (cccd != null) {
|
||||
enableNotification(chr.getUuid());
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if ((mGatt.getServices().size() == 0) && mIsChromebook && !mIsReconnecting) {
|
||||
Log.e(TAG, "Chromebook: Discovered services were empty; this almost certainly means the BtGatt.ContextMap bug has bitten us.");
|
||||
mIsConnected = false;
|
||||
mIsReconnecting = true;
|
||||
mGatt.disconnect();
|
||||
mGatt = connectGatt(false);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
private void finishCurrentGattOperation() {
|
||||
GattOperation op = null;
|
||||
synchronized (mOperations) {
|
||||
if (mCurrentOperation != null) {
|
||||
op = mCurrentOperation;
|
||||
mCurrentOperation = null;
|
||||
}
|
||||
}
|
||||
if (op != null) {
|
||||
boolean result = op.finish(); // TODO: Maybe in main thread as well?
|
||||
|
||||
// Our operation failed, let's add it back to the beginning of our queue.
|
||||
if (!result) {
|
||||
mOperations.addFirst(op);
|
||||
}
|
||||
}
|
||||
executeNextGattOperation();
|
||||
}
|
||||
|
||||
private void executeNextGattOperation() {
|
||||
synchronized (mOperations) {
|
||||
if (mCurrentOperation != null)
|
||||
return;
|
||||
|
||||
if (mOperations.isEmpty())
|
||||
return;
|
||||
|
||||
mCurrentOperation = mOperations.removeFirst();
|
||||
}
|
||||
|
||||
Runnable gattOperationRunnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized (mOperations) {
|
||||
if (mCurrentOperation == null) {
|
||||
Log.e(TAG, "Current operation null in executor?");
|
||||
return;
|
||||
}
|
||||
|
||||
mCurrentOperation.run();
|
||||
// now wait for the GATT callback and when it comes, finish this operation
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (mCurrentOperation.getDelayMs() == 0) {
|
||||
// Run in main thread
|
||||
mHandler.post(gattOperationRunnable);
|
||||
}
|
||||
else {
|
||||
// If we have a delay on this operation, wait before we post it.
|
||||
mHandler.postDelayed(gattOperationRunnable, mCurrentOperation.getDelayMs());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void queueGattOperation(GattOperation op) {
|
||||
synchronized (mOperations) {
|
||||
mOperations.add(op);
|
||||
}
|
||||
executeNextGattOperation();
|
||||
}
|
||||
|
||||
private void enableNotification(UUID chrUuid) {
|
||||
// Add a 500ms delay to notification write for Amazon Fire TV devices, as otherwise if we do this too quickly after connecting
|
||||
// it will return success and then silently drop the operation on the floor.
|
||||
GattOperation op = HIDDeviceBLESteamController.GattOperation.enableNotification(mGatt, chrUuid, 500);
|
||||
queueGattOperation(op);
|
||||
|
||||
// Amazon Fire devices can also silently timeout on writeDescriptor, so
|
||||
// set up a little delayed check that will attempt to write a second time.
|
||||
//
|
||||
// While this only seems to be needed on Amazon Fire TV devices at present, it
|
||||
// doesn't hurt to have a retry on other devices as well.
|
||||
//
|
||||
final HIDDeviceBLESteamController finalThis = this;
|
||||
final UUID finalUuid = chrUuid;
|
||||
mHandler.postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (!finalThis.mHasEnabledNotifications) {
|
||||
|
||||
if (finalThis.mHasSeenInputUpdate) {
|
||||
// Amazon Five devices may have enabled notifications on the input characteristic and not given us a callback. If we've seen
|
||||
// input reports, though, somewhat by definition notifications are enabled.
|
||||
Log.w(TAG, "WriteDescriptor has never returned, but we've seen input reports. Moving on with controller initialization.");
|
||||
finalThis.mHasEnabledNotifications = true;
|
||||
finalThis.enableValveMode();
|
||||
return;
|
||||
}
|
||||
|
||||
// Give one more try.
|
||||
GattOperation retry = HIDDeviceBLESteamController.GattOperation.enableNotification(finalThis.mGatt, finalUuid, 500);
|
||||
finalThis.queueGattOperation(retry);
|
||||
}
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
void writeCharacteristic(UUID uuid, byte[] value) {
|
||||
GattOperation op = HIDDeviceBLESteamController.GattOperation.writeCharacteristic(mGatt, uuid, value);
|
||||
queueGattOperation(op);
|
||||
}
|
||||
|
||||
void readCharacteristic(UUID uuid) {
|
||||
GattOperation op = HIDDeviceBLESteamController.GattOperation.readCharacteristic(mGatt, uuid);
|
||||
queueGattOperation(op);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
////////////// BluetoothGattCallback overridden methods
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@Override
|
||||
public void onConnectionStateChange(BluetoothGatt g, int status, int newState) {
|
||||
//Log.v(TAG, "onConnectionStateChange status=" + status + " newState=" + newState);
|
||||
mIsReconnecting = false;
|
||||
if (newState == 2) {
|
||||
mIsConnected = true;
|
||||
// Run directly, without GattOperation
|
||||
if (!isRegistered()) {
|
||||
mHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
mGatt.discoverServices();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (newState == 0) {
|
||||
mIsConnected = false;
|
||||
}
|
||||
|
||||
// Disconnection is handled in SteamLink using the ACTION_ACL_DISCONNECTED Intent.
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
|
||||
//Log.v(TAG, "onServicesDiscovered status=" + status);
|
||||
if (status == 0) {
|
||||
if (gatt.getServices().size() == 0) {
|
||||
Log.v(TAG, "onServicesDiscovered returned zero services; something has gone horribly wrong down in Android's Bluetooth stack.");
|
||||
mIsReconnecting = true;
|
||||
mIsConnected = false;
|
||||
gatt.disconnect();
|
||||
mGatt = connectGatt(false);
|
||||
} else {
|
||||
if (getProductId() == TRITON_BLE_PID) {
|
||||
// Android will not properly play well with Data Length Extensions without manually requesting a large MTU,
|
||||
// and Triton controllers require DLE support.
|
||||
//
|
||||
// 517 is basically a "magic number" as far as Android's bluetooth code is concerned, so do not change
|
||||
// this value. It is functionally "please enable data length extensions" on some Android builds.
|
||||
mGatt.requestMtu(517);
|
||||
}
|
||||
|
||||
probeService(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
|
||||
//Log.v(TAG, "onCharacteristicRead status=" + status + " uuid=" + characteristic.getUuid());
|
||||
|
||||
if (characteristic.getUuid().equals(reportCharacteristic) && !mFrozen) {
|
||||
mManager.HIDDeviceReportResponse(getId(), characteristic.getValue());
|
||||
}
|
||||
|
||||
finishCurrentGattOperation();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
|
||||
//Log.v(TAG, "onCharacteristicWrite status=" + status + " uuid=" + characteristic.getUuid());
|
||||
|
||||
if (characteristic.getUuid().equals(reportCharacteristic)) {
|
||||
// Only register controller with the native side once it has been fully configured
|
||||
if (!isRegistered()) {
|
||||
Log.v(TAG, "Registering Steam Controller with ID: " + getId());
|
||||
mManager.HIDDeviceConnected(getId(), getIdentifier(), getVendorId(), getProductId(), getSerialNumber(), getVersion(), getManufacturerName(), getProductName(), 0, 0, 0, 0, true, mReportId);
|
||||
setRegistered();
|
||||
}
|
||||
}
|
||||
|
||||
finishCurrentGattOperation();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
|
||||
// Enable this for verbose logging of controller input reports
|
||||
//Log.v(TAG, "onCharacteristicChanged uuid=" + characteristic.getUuid() + " data=" + HexDump.dumpHexString(characteristic.getValue()));
|
||||
|
||||
if (characteristic.getUuid().equals(mInputCharacteristic) && !mFrozen) {
|
||||
mHasSeenInputUpdate = true;
|
||||
mManager.HIDDeviceInputReport(getId(), characteristic.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
|
||||
//Log.v(TAG, "onDescriptorRead status=" + status);
|
||||
}
|
||||
|
||||
private void enableValveMode()
|
||||
{
|
||||
BluetoothGattService valveService = mGatt.getService(steamControllerService);
|
||||
if (valveService == null)
|
||||
return;
|
||||
|
||||
BluetoothGattCharacteristic reportChr = valveService.getCharacteristic(reportCharacteristic);
|
||||
if (reportChr != null) {
|
||||
if (getProductId() == TRITON_BLE_PID) {
|
||||
// For Triton we just mark things registered.
|
||||
Log.v(TAG, "Registering Triton Steam Controller with ID: " + getId());
|
||||
mManager.HIDDeviceConnected(getId(), getIdentifier(), getVendorId(), getProductId(), getSerialNumber(), getVersion(), getManufacturerName(), getProductName(), 0, 0, 0, 0, true, mReportId);
|
||||
setRegistered();
|
||||
} else {
|
||||
// For the original controller, we need to manually enter Valve mode.
|
||||
Log.v(TAG, "Writing report characteristic to enter valve mode");
|
||||
reportChr.setValue(enterValveMode);
|
||||
mGatt.writeCharacteristic(reportChr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
|
||||
BluetoothGattCharacteristic chr = descriptor.getCharacteristic();
|
||||
//Log.v(TAG, "onDescriptorWrite status=" + status + " uuid=" + chr.getUuid() + " descriptor=" + descriptor.getUuid());
|
||||
|
||||
if (chr.getUuid().equals(mInputCharacteristic)) {
|
||||
mHasEnabledNotifications = true;
|
||||
enableValveMode();
|
||||
}
|
||||
|
||||
finishCurrentGattOperation();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
|
||||
//Log.v(TAG, "onReliableWriteCompleted status=" + status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
|
||||
//Log.v(TAG, "onReadRemoteRssi status=" + status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
|
||||
//Log.v(TAG, "onMtuChanged status=" + status);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//////// Public API
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@Override
|
||||
public int getId() {
|
||||
return mDeviceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getVendorId() {
|
||||
// Valve Corporation
|
||||
final int VALVE_USB_VID = 0x28DE;
|
||||
return VALVE_USB_VID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getProductId() {
|
||||
if (mProductId > 0) {
|
||||
// We've already set a product ID.
|
||||
return mProductId;
|
||||
}
|
||||
|
||||
if (mDevice.getName().startsWith("Steam Ctrl")) {
|
||||
// We're a newer Triton device
|
||||
mProductId = TRITON_BLE_PID;
|
||||
} else {
|
||||
// We're an OG Steam Controller
|
||||
mProductId = D0G_BLE2_PID;
|
||||
}
|
||||
|
||||
return mProductId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSerialNumber() {
|
||||
// This will be read later via feature report by Steam
|
||||
return "12345";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getVersion() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getManufacturerName() {
|
||||
return "Valve Corporation";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getProductName() {
|
||||
return "Steam Controller";
|
||||
}
|
||||
|
||||
@Override
|
||||
public UsbDevice getDevice() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean open() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int writeReport(byte[] report, boolean feature) {
|
||||
if (!isRegistered()) {
|
||||
Log.e(TAG, "Attempted writeReport before Steam Controller is registered!");
|
||||
if (mIsConnected) {
|
||||
probeService(this);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (feature) {
|
||||
// We need to skip the first byte, as that doesn't go over the air
|
||||
byte[] actual_report = Arrays.copyOfRange(report, 1, report.length - 1);
|
||||
//Log.v(TAG, "writeFeatureReport " + HexDump.dumpHexString(actual_report));
|
||||
writeCharacteristic(reportCharacteristic, actual_report);
|
||||
return report.length;
|
||||
} else {
|
||||
// If we're an original-recipe Steam Controller we just write to the characteristic directly.
|
||||
if (getProductId() == D0G_BLE2_PID) {
|
||||
//Log.v(TAG, "writeOutputReport " + HexDump.dumpHexString(report));
|
||||
writeCharacteristic(reportCharacteristic, report);
|
||||
return report.length;
|
||||
}
|
||||
|
||||
// If we're a Triton, we need to find the correct report characteristic.
|
||||
if (report.length > 0) {
|
||||
int reportId = report[0] & 0xFF;
|
||||
BluetoothGattCharacteristic targetedReportCharacteristic = mOutputReportChars.get(reportId);
|
||||
if (targetedReportCharacteristic != null) {
|
||||
byte[] actual_report = Arrays.copyOfRange(report, 1, report.length - 1);
|
||||
//Log.v(TAG, "writeOutputReport 0x" + Integer.toString(reportId, 16) + " " + HexDump.dumpHexString(report));
|
||||
writeCharacteristic(targetedReportCharacteristic.getUuid(), actual_report);
|
||||
return report.length;
|
||||
} else {
|
||||
Log.w(TAG, "Got report write request for unknown report type 0x" + Integer.toString(reportId, 16));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean readReport(byte[] report, boolean feature) {
|
||||
if (!isRegistered()) {
|
||||
Log.e(TAG, "Attempted readReport before Steam Controller is registered!");
|
||||
if (mIsConnected) {
|
||||
probeService(this);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (feature) {
|
||||
readCharacteristic(reportCharacteristic);
|
||||
return true;
|
||||
} else {
|
||||
// Not implemented
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFrozen(boolean frozen) {
|
||||
mFrozen = frozen;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
close();
|
||||
|
||||
BluetoothGatt g = mGatt;
|
||||
if (g != null) {
|
||||
g.disconnect();
|
||||
g.close();
|
||||
mGatt = null;
|
||||
}
|
||||
mManager = null;
|
||||
mIsRegistered = false;
|
||||
mIsConnected = false;
|
||||
mOperations.clear();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,707 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.AlertDialog;
|
||||
import android.app.PendingIntent;
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.bluetooth.BluetoothDevice;
|
||||
import android.bluetooth.BluetoothManager;
|
||||
import android.bluetooth.BluetoothProfile;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.hardware.usb.*;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public class HIDDeviceManager {
|
||||
private static final String TAG = "hidapi";
|
||||
private static final String ACTION_USB_PERMISSION = "org.libsdl.app.USB_PERMISSION";
|
||||
|
||||
private static HIDDeviceManager sManager;
|
||||
private static int sManagerRefCount = 0;
|
||||
|
||||
static public HIDDeviceManager acquire(Context context) {
|
||||
if (sManagerRefCount == 0) {
|
||||
sManager = new HIDDeviceManager(context);
|
||||
}
|
||||
++sManagerRefCount;
|
||||
return sManager;
|
||||
}
|
||||
|
||||
static public void release(HIDDeviceManager manager) {
|
||||
if (manager == sManager) {
|
||||
--sManagerRefCount;
|
||||
if (sManagerRefCount == 0) {
|
||||
sManager.close();
|
||||
sManager = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Context mContext;
|
||||
private HashMap<Integer, HIDDevice> mDevicesById = new HashMap<Integer, HIDDevice>();
|
||||
private HashMap<BluetoothDevice, HIDDeviceBLESteamController> mBluetoothDevices = new HashMap<BluetoothDevice, HIDDeviceBLESteamController>();
|
||||
private int mNextDeviceId = 0;
|
||||
private SharedPreferences mSharedPreferences = null;
|
||||
private boolean mIsChromebook = false;
|
||||
private UsbManager mUsbManager;
|
||||
private Handler mHandler;
|
||||
private BluetoothManager mBluetoothManager;
|
||||
private List<BluetoothDevice> mLastBluetoothDevices;
|
||||
|
||||
private final BroadcastReceiver mUsbBroadcast = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String action = intent.getAction();
|
||||
if (action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
|
||||
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
|
||||
handleUsbDeviceAttached(usbDevice);
|
||||
} else if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
|
||||
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
|
||||
handleUsbDeviceDetached(usbDevice);
|
||||
} else if (action.equals(HIDDeviceManager.ACTION_USB_PERMISSION)) {
|
||||
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
|
||||
handleUsbDevicePermission(usbDevice, intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private final BroadcastReceiver mBluetoothBroadcast = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String action = intent.getAction();
|
||||
// Bluetooth device was connected. If it was a Steam Controller, handle it
|
||||
if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
|
||||
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
|
||||
Log.d(TAG, "Bluetooth device connected: " + device);
|
||||
|
||||
if (isSteamController(device)) {
|
||||
connectBluetoothDevice(device);
|
||||
}
|
||||
}
|
||||
|
||||
// Bluetooth device was disconnected, remove from controller manager (if any)
|
||||
if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
|
||||
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
|
||||
Log.d(TAG, "Bluetooth device disconnected: " + device);
|
||||
|
||||
disconnectBluetoothDevice(device);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private HIDDeviceManager(final Context context) {
|
||||
mContext = context;
|
||||
|
||||
HIDDeviceRegisterCallback();
|
||||
|
||||
mSharedPreferences = mContext.getSharedPreferences("hidapi", Context.MODE_PRIVATE);
|
||||
mIsChromebook = SDLActivity.isChromebook();
|
||||
|
||||
// if (shouldClear) {
|
||||
// SharedPreferences.Editor spedit = mSharedPreferences.edit();
|
||||
// spedit.clear();
|
||||
// spedit.apply();
|
||||
// }
|
||||
// else
|
||||
{
|
||||
mNextDeviceId = mSharedPreferences.getInt("next_device_id", 0);
|
||||
}
|
||||
}
|
||||
|
||||
Context getContext() {
|
||||
return mContext;
|
||||
}
|
||||
|
||||
int getDeviceIDForIdentifier(String identifier) {
|
||||
SharedPreferences.Editor spedit = mSharedPreferences.edit();
|
||||
|
||||
int result = mSharedPreferences.getInt(identifier, 0);
|
||||
if (result == 0) {
|
||||
result = mNextDeviceId++;
|
||||
spedit.putInt("next_device_id", mNextDeviceId);
|
||||
}
|
||||
|
||||
spedit.putInt(identifier, result);
|
||||
spedit.apply();
|
||||
return result;
|
||||
}
|
||||
|
||||
private void initializeUSB() {
|
||||
mUsbManager = (UsbManager)mContext.getSystemService(Context.USB_SERVICE);
|
||||
if (mUsbManager == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
// Logging
|
||||
for (UsbDevice device : mUsbManager.getDeviceList().values()) {
|
||||
Log.i(TAG,"Path: " + device.getDeviceName());
|
||||
Log.i(TAG,"Manufacturer: " + device.getManufacturerName());
|
||||
Log.i(TAG,"Product: " + device.getProductName());
|
||||
Log.i(TAG,"ID: " + device.getDeviceId());
|
||||
Log.i(TAG,"Class: " + device.getDeviceClass());
|
||||
Log.i(TAG,"Protocol: " + device.getDeviceProtocol());
|
||||
Log.i(TAG,"Vendor ID " + device.getVendorId());
|
||||
Log.i(TAG,"Product ID: " + device.getProductId());
|
||||
Log.i(TAG,"Interface count: " + device.getInterfaceCount());
|
||||
Log.i(TAG,"---------------------------------------");
|
||||
|
||||
// Get interface details
|
||||
for (int index = 0; index < device.getInterfaceCount(); index++) {
|
||||
UsbInterface mUsbInterface = device.getInterface(index);
|
||||
Log.i(TAG," ***** *****");
|
||||
Log.i(TAG," Interface index: " + index);
|
||||
Log.i(TAG," Interface ID: " + mUsbInterface.getId());
|
||||
Log.i(TAG," Interface class: " + mUsbInterface.getInterfaceClass());
|
||||
Log.i(TAG," Interface subclass: " + mUsbInterface.getInterfaceSubclass());
|
||||
Log.i(TAG," Interface protocol: " + mUsbInterface.getInterfaceProtocol());
|
||||
Log.i(TAG," Endpoint count: " + mUsbInterface.getEndpointCount());
|
||||
|
||||
// Get endpoint details
|
||||
for (int epi = 0; epi < mUsbInterface.getEndpointCount(); epi++)
|
||||
{
|
||||
UsbEndpoint mEndpoint = mUsbInterface.getEndpoint(epi);
|
||||
Log.i(TAG," ++++ ++++ ++++");
|
||||
Log.i(TAG," Endpoint index: " + epi);
|
||||
Log.i(TAG," Attributes: " + mEndpoint.getAttributes());
|
||||
Log.i(TAG," Direction: " + mEndpoint.getDirection());
|
||||
Log.i(TAG," Number: " + mEndpoint.getEndpointNumber());
|
||||
Log.i(TAG," Interval: " + mEndpoint.getInterval());
|
||||
Log.i(TAG," Packet size: " + mEndpoint.getMaxPacketSize());
|
||||
Log.i(TAG," Type: " + mEndpoint.getType());
|
||||
}
|
||||
}
|
||||
}
|
||||
Log.i(TAG," No more devices connected.");
|
||||
*/
|
||||
|
||||
// Register for USB broadcasts and permission completions
|
||||
IntentFilter filter = new IntentFilter();
|
||||
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
|
||||
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
|
||||
filter.addAction(HIDDeviceManager.ACTION_USB_PERMISSION);
|
||||
if (Build.VERSION.SDK_INT >= 33) { /* Android 13.0 (TIRAMISU) */
|
||||
mContext.registerReceiver(mUsbBroadcast, filter, Context.RECEIVER_EXPORTED);
|
||||
} else {
|
||||
mContext.registerReceiver(mUsbBroadcast, filter);
|
||||
}
|
||||
|
||||
for (UsbDevice usbDevice : mUsbManager.getDeviceList().values()) {
|
||||
handleUsbDeviceAttached(usbDevice);
|
||||
}
|
||||
}
|
||||
|
||||
UsbManager getUSBManager() {
|
||||
return mUsbManager;
|
||||
}
|
||||
|
||||
private void shutdownUSB() {
|
||||
try {
|
||||
mContext.unregisterReceiver(mUsbBroadcast);
|
||||
} catch (Exception e) {
|
||||
// We may not have registered, that's okay
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isHIDDeviceInterface(UsbDevice usbDevice, UsbInterface usbInterface) {
|
||||
if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_HID) {
|
||||
return true;
|
||||
}
|
||||
if (isXbox360Controller(usbDevice, usbInterface) || isXboxOneController(usbDevice, usbInterface)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean isXbox360Controller(UsbDevice usbDevice, UsbInterface usbInterface) {
|
||||
final int XB360_IFACE_SUBCLASS = 93;
|
||||
final int XB360_IFACE_PROTOCOL = 1; // Wired
|
||||
final int XB360W_IFACE_PROTOCOL = 129; // Wireless
|
||||
final int[] SUPPORTED_VENDORS = {
|
||||
0x0079, // GPD Win 2
|
||||
0x0351, // CRKD
|
||||
0x044f, // Thrustmaster
|
||||
0x045e, // Microsoft
|
||||
0x046d, // Logitech
|
||||
0x056e, // Elecom
|
||||
0x06a3, // Saitek
|
||||
0x0738, // Mad Catz
|
||||
0x07ff, // Mad Catz
|
||||
0x0e6f, // PDP
|
||||
0x0f0d, // Hori
|
||||
0x1038, // SteelSeries
|
||||
0x10f5, // Turtle Beach
|
||||
0x11c9, // Nacon
|
||||
0x1209, // Generic
|
||||
0x12ab, // Unknown
|
||||
0x1430, // RedOctane
|
||||
0x146b, // BigBen
|
||||
0x1532, // Razer Sabertooth
|
||||
0x15e4, // Numark
|
||||
0x162e, // Joytech
|
||||
0x1689, // Razer Onza
|
||||
0x1949, // Lab126, Inc.
|
||||
0x1bad, // Harmonix
|
||||
0x20d6, // PowerA
|
||||
0x24c6, // PowerA
|
||||
0x2c22, // Qanba
|
||||
0x2dc8, // 8BitDo
|
||||
0x3537, // GameSir
|
||||
0x3651, // CRKD
|
||||
0x37d7, // Flydigi
|
||||
0x3958, // Red Octane Games
|
||||
0x9886, // ASTRO Gaming
|
||||
};
|
||||
|
||||
if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_VENDOR_SPEC &&
|
||||
usbInterface.getInterfaceSubclass() == XB360_IFACE_SUBCLASS &&
|
||||
(usbInterface.getInterfaceProtocol() == XB360_IFACE_PROTOCOL ||
|
||||
usbInterface.getInterfaceProtocol() == XB360W_IFACE_PROTOCOL)) {
|
||||
int vendor_id = usbDevice.getVendorId();
|
||||
for (int supportedVid : SUPPORTED_VENDORS) {
|
||||
if (vendor_id == supportedVid) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean isXboxOneController(UsbDevice usbDevice, UsbInterface usbInterface) {
|
||||
final int XB1_IFACE_SUBCLASS = 71;
|
||||
final int XB1_IFACE_PROTOCOL = 208;
|
||||
final int[] SUPPORTED_VENDORS = {
|
||||
0x0351, // CRKD
|
||||
0x03f0, // HP
|
||||
0x044f, // Thrustmaster
|
||||
0x045e, // Microsoft
|
||||
0x0738, // Mad Catz
|
||||
0x0b05, // ASUS
|
||||
0x0e6f, // PDP
|
||||
0x0f0d, // Hori
|
||||
0x10f5, // Turtle Beach
|
||||
0x1209, // Generic
|
||||
0x1532, // Razer Wildcat
|
||||
0x20d6, // PowerA
|
||||
0x24c6, // PowerA
|
||||
0x294b, // Snakebyte
|
||||
0x2dc8, // 8BitDo
|
||||
0x2e24, // Hyperkin
|
||||
0x2e95, // SCUF
|
||||
0x3285, // Nacon
|
||||
0x3537, // GameSir
|
||||
0x3651, // CRKD
|
||||
0x366c, // ByoWave
|
||||
0x3958, // Red Octane Games
|
||||
};
|
||||
|
||||
if (usbInterface.getId() == 0 &&
|
||||
usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_VENDOR_SPEC &&
|
||||
usbInterface.getInterfaceSubclass() == XB1_IFACE_SUBCLASS &&
|
||||
usbInterface.getInterfaceProtocol() == XB1_IFACE_PROTOCOL) {
|
||||
int vendor_id = usbDevice.getVendorId();
|
||||
for (int supportedVid : SUPPORTED_VENDORS) {
|
||||
if (vendor_id == supportedVid) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void handleUsbDeviceAttached(UsbDevice usbDevice) {
|
||||
connectHIDDeviceUSB(usbDevice);
|
||||
}
|
||||
|
||||
private void handleUsbDeviceDetached(UsbDevice usbDevice) {
|
||||
List<Integer> devices = new ArrayList<Integer>();
|
||||
for (HIDDevice device : mDevicesById.values()) {
|
||||
if (usbDevice.equals(device.getDevice())) {
|
||||
devices.add(device.getId());
|
||||
}
|
||||
}
|
||||
for (int id : devices) {
|
||||
HIDDevice device = mDevicesById.get(id);
|
||||
mDevicesById.remove(id);
|
||||
device.shutdown();
|
||||
HIDDeviceDisconnected(id);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleUsbDevicePermission(UsbDevice usbDevice, boolean permission_granted) {
|
||||
for (HIDDevice device : mDevicesById.values()) {
|
||||
if (usbDevice.equals(device.getDevice())) {
|
||||
boolean opened = false;
|
||||
if (permission_granted) {
|
||||
opened = device.open();
|
||||
}
|
||||
HIDDeviceOpenResult(device.getId(), opened);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void connectHIDDeviceUSB(UsbDevice usbDevice) {
|
||||
synchronized (this) {
|
||||
int interface_mask = 0;
|
||||
for (int interface_index = 0; interface_index < usbDevice.getInterfaceCount(); interface_index++) {
|
||||
UsbInterface usbInterface = usbDevice.getInterface(interface_index);
|
||||
if (isHIDDeviceInterface(usbDevice, usbInterface)) {
|
||||
// Check to see if we've already added this interface
|
||||
// This happens with the Xbox Series X controller which has a duplicate interface 0, which is inactive
|
||||
int interface_id = usbInterface.getId();
|
||||
if ((interface_mask & (1 << interface_id)) != 0) {
|
||||
continue;
|
||||
}
|
||||
interface_mask |= (1 << interface_id);
|
||||
|
||||
HIDDeviceUSB device = new HIDDeviceUSB(this, usbDevice, interface_index);
|
||||
int id = device.getId();
|
||||
mDevicesById.put(id, device);
|
||||
HIDDeviceConnected(id, device.getIdentifier(), device.getVendorId(), device.getProductId(), device.getSerialNumber(), device.getVersion(), device.getManufacturerName(), device.getProductName(), usbInterface.getId(), usbInterface.getInterfaceClass(), usbInterface.getInterfaceSubclass(), usbInterface.getInterfaceProtocol(), false, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void initializeBluetooth() {
|
||||
Log.d(TAG, "Initializing Bluetooth");
|
||||
|
||||
if (Build.VERSION.SDK_INT >= 31 /* Android 12 */ &&
|
||||
mContext.getPackageManager().checkPermission(android.Manifest.permission.BLUETOOTH_CONNECT, mContext.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
|
||||
Log.d(TAG, "Couldn't initialize Bluetooth, missing android.permission.BLUETOOTH_CONNECT");
|
||||
return;
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT <= 30 /* Android 11.0 (R) */ &&
|
||||
mContext.getPackageManager().checkPermission(android.Manifest.permission.BLUETOOTH, mContext.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
|
||||
Log.d(TAG, "Couldn't initialize Bluetooth, missing android.permission.BLUETOOTH");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
|
||||
Log.d(TAG, "Couldn't initialize Bluetooth, this version of Android does not support Bluetooth LE");
|
||||
return;
|
||||
}
|
||||
|
||||
// Find bonded bluetooth controllers and create SteamControllers for them
|
||||
mBluetoothManager = (BluetoothManager)mContext.getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
if (mBluetoothManager == null) {
|
||||
// This device doesn't support Bluetooth.
|
||||
return;
|
||||
}
|
||||
|
||||
BluetoothAdapter btAdapter = mBluetoothManager.getAdapter();
|
||||
if (btAdapter == null) {
|
||||
// This device has Bluetooth support in the codebase, but has no available adapters.
|
||||
return;
|
||||
}
|
||||
|
||||
// Get our bonded devices.
|
||||
for (BluetoothDevice device : btAdapter.getBondedDevices()) {
|
||||
|
||||
Log.d(TAG, "Bluetooth device available: " + device);
|
||||
if (isSteamController(device)) {
|
||||
connectBluetoothDevice(device);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// NOTE: These don't work on Chromebooks, to my undying dismay.
|
||||
IntentFilter filter = new IntentFilter();
|
||||
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
|
||||
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
|
||||
if (Build.VERSION.SDK_INT >= 33) { /* Android 13.0 (TIRAMISU) */
|
||||
mContext.registerReceiver(mBluetoothBroadcast, filter, Context.RECEIVER_EXPORTED);
|
||||
} else {
|
||||
mContext.registerReceiver(mBluetoothBroadcast, filter);
|
||||
}
|
||||
|
||||
if (mIsChromebook) {
|
||||
mHandler = new Handler(Looper.getMainLooper());
|
||||
mLastBluetoothDevices = new ArrayList<BluetoothDevice>();
|
||||
|
||||
// final HIDDeviceManager finalThis = this;
|
||||
// mHandler.postDelayed(new Runnable() {
|
||||
// @Override
|
||||
// public void run() {
|
||||
// finalThis.chromebookConnectionHandler();
|
||||
// }
|
||||
// }, 5000);
|
||||
}
|
||||
}
|
||||
|
||||
private void shutdownBluetooth() {
|
||||
try {
|
||||
mContext.unregisterReceiver(mBluetoothBroadcast);
|
||||
} catch (Exception e) {
|
||||
// We may not have registered, that's okay
|
||||
}
|
||||
}
|
||||
|
||||
// Chromebooks do not pass along ACTION_ACL_CONNECTED / ACTION_ACL_DISCONNECTED properly.
|
||||
// This function provides a sort of dummy version of that, watching for changes in the
|
||||
// connected devices and attempting to add controllers as things change.
|
||||
void chromebookConnectionHandler() {
|
||||
if (!mIsChromebook) {
|
||||
return;
|
||||
}
|
||||
|
||||
ArrayList<BluetoothDevice> disconnected = new ArrayList<BluetoothDevice>();
|
||||
ArrayList<BluetoothDevice> connected = new ArrayList<BluetoothDevice>();
|
||||
|
||||
List<BluetoothDevice> currentConnected = mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT);
|
||||
|
||||
for (BluetoothDevice bluetoothDevice : currentConnected) {
|
||||
if (!mLastBluetoothDevices.contains(bluetoothDevice)) {
|
||||
connected.add(bluetoothDevice);
|
||||
}
|
||||
}
|
||||
for (BluetoothDevice bluetoothDevice : mLastBluetoothDevices) {
|
||||
if (!currentConnected.contains(bluetoothDevice)) {
|
||||
disconnected.add(bluetoothDevice);
|
||||
}
|
||||
}
|
||||
|
||||
mLastBluetoothDevices = currentConnected;
|
||||
|
||||
for (BluetoothDevice bluetoothDevice : disconnected) {
|
||||
disconnectBluetoothDevice(bluetoothDevice);
|
||||
}
|
||||
for (BluetoothDevice bluetoothDevice : connected) {
|
||||
connectBluetoothDevice(bluetoothDevice);
|
||||
}
|
||||
|
||||
final HIDDeviceManager finalThis = this;
|
||||
mHandler.postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
finalThis.chromebookConnectionHandler();
|
||||
}
|
||||
}, 10000);
|
||||
}
|
||||
|
||||
boolean connectBluetoothDevice(BluetoothDevice bluetoothDevice) {
|
||||
Log.v(TAG, "connectBluetoothDevice device=" + bluetoothDevice);
|
||||
synchronized (this) {
|
||||
if (mBluetoothDevices.containsKey(bluetoothDevice)) {
|
||||
Log.v(TAG, "Steam controller with address " + bluetoothDevice + " already exists, attempting reconnect");
|
||||
|
||||
HIDDeviceBLESteamController device = mBluetoothDevices.get(bluetoothDevice);
|
||||
device.reconnect();
|
||||
|
||||
return false;
|
||||
}
|
||||
HIDDeviceBLESteamController device = new HIDDeviceBLESteamController(this, bluetoothDevice);
|
||||
int id = device.getId();
|
||||
mBluetoothDevices.put(bluetoothDevice, device);
|
||||
mDevicesById.put(id, device);
|
||||
|
||||
// The Steam Controller will mark itself connected once initialization is complete
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void disconnectBluetoothDevice(BluetoothDevice bluetoothDevice) {
|
||||
synchronized (this) {
|
||||
HIDDeviceBLESteamController device = mBluetoothDevices.get(bluetoothDevice);
|
||||
if (device == null)
|
||||
return;
|
||||
|
||||
int id = device.getId();
|
||||
mBluetoothDevices.remove(bluetoothDevice);
|
||||
mDevicesById.remove(id);
|
||||
device.shutdown();
|
||||
HIDDeviceDisconnected(id);
|
||||
}
|
||||
}
|
||||
|
||||
boolean isSteamController(BluetoothDevice bluetoothDevice) {
|
||||
// Sanity check. If you pass in a null device, by definition it is never a Steam Controller.
|
||||
if (bluetoothDevice == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If the device has no local name, we really don't want to try an equality check against it.
|
||||
if (bluetoothDevice.getName() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Steam Controllers will always support Bluetooth Low Energy
|
||||
if ((bluetoothDevice.getType() & BluetoothDevice.DEVICE_TYPE_LE) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Match on the name either the original Steam Controller or the new second-generation one advertise with.
|
||||
return bluetoothDevice.getName().equals("SteamController") || bluetoothDevice.getName().startsWith("Steam Ctrl");
|
||||
}
|
||||
|
||||
private void close() {
|
||||
shutdownUSB();
|
||||
shutdownBluetooth();
|
||||
synchronized (this) {
|
||||
for (HIDDevice device : mDevicesById.values()) {
|
||||
device.shutdown();
|
||||
}
|
||||
mDevicesById.clear();
|
||||
mBluetoothDevices.clear();
|
||||
HIDDeviceReleaseCallback();
|
||||
}
|
||||
}
|
||||
|
||||
public void setFrozen(boolean frozen) {
|
||||
synchronized (this) {
|
||||
for (HIDDevice device : mDevicesById.values()) {
|
||||
device.setFrozen(frozen);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
private HIDDevice getDevice(int id) {
|
||||
synchronized (this) {
|
||||
HIDDevice result = mDevicesById.get(id);
|
||||
if (result == null) {
|
||||
Log.v(TAG, "No device for id: " + id);
|
||||
Log.v(TAG, "Available devices: " + mDevicesById.keySet());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
////////// JNI interface functions
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
boolean initialize(boolean usb, boolean bluetooth) {
|
||||
Log.v(TAG, "initialize(" + usb + ", " + bluetooth + ")");
|
||||
|
||||
if (usb) {
|
||||
initializeUSB();
|
||||
}
|
||||
if (bluetooth) {
|
||||
initializeBluetooth();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean openDevice(int deviceID) {
|
||||
Log.v(TAG, "openDevice deviceID=" + deviceID);
|
||||
HIDDevice device = getDevice(deviceID);
|
||||
if (device == null) {
|
||||
HIDDeviceDisconnected(deviceID);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Look to see if this is a USB device and we have permission to access it
|
||||
UsbDevice usbDevice = device.getDevice();
|
||||
if (usbDevice != null && !mUsbManager.hasPermission(usbDevice)) {
|
||||
HIDDeviceOpenPending(deviceID);
|
||||
try {
|
||||
final int FLAG_MUTABLE = 0x02000000; // PendingIntent.FLAG_MUTABLE, but don't require SDK 31
|
||||
int flags;
|
||||
if (Build.VERSION.SDK_INT >= 31 /* Android 12.0 (S) */) {
|
||||
flags = FLAG_MUTABLE;
|
||||
} else {
|
||||
flags = 0;
|
||||
}
|
||||
|
||||
Intent intent = new Intent(HIDDeviceManager.ACTION_USB_PERMISSION);
|
||||
intent.setPackage(mContext.getPackageName());
|
||||
mUsbManager.requestPermission(usbDevice, PendingIntent.getBroadcast(mContext, 0, intent, flags));
|
||||
} catch (Exception e) {
|
||||
Log.v(TAG, "Couldn't request permission for USB device " + usbDevice);
|
||||
HIDDeviceOpenResult(deviceID, false);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return device.open();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Got exception: " + Log.getStackTraceString(e));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
int writeReport(int deviceID, byte[] report, boolean feature) {
|
||||
try {
|
||||
//Log.v(TAG, "writeReport deviceID=" + deviceID + " length=" + report.length);
|
||||
HIDDevice device;
|
||||
device = getDevice(deviceID);
|
||||
if (device == null) {
|
||||
HIDDeviceDisconnected(deviceID);
|
||||
return -1;
|
||||
}
|
||||
|
||||
return device.writeReport(report, feature);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Got exception: " + Log.getStackTraceString(e));
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
boolean readReport(int deviceID, byte[] report, boolean feature) {
|
||||
try {
|
||||
//Log.v(TAG, "readReport deviceID=" + deviceID);
|
||||
HIDDevice device;
|
||||
device = getDevice(deviceID);
|
||||
if (device == null) {
|
||||
HIDDeviceDisconnected(deviceID);
|
||||
return false;
|
||||
}
|
||||
|
||||
return device.readReport(report, feature);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Got exception: " + Log.getStackTraceString(e));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void closeDevice(int deviceID) {
|
||||
try {
|
||||
Log.v(TAG, "closeDevice deviceID=" + deviceID);
|
||||
HIDDevice device;
|
||||
device = getDevice(deviceID);
|
||||
if (device == null) {
|
||||
HIDDeviceDisconnected(deviceID);
|
||||
return;
|
||||
}
|
||||
|
||||
device.close();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Got exception: " + Log.getStackTraceString(e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/////////////// Native methods
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
private native void HIDDeviceRegisterCallback();
|
||||
private native void HIDDeviceReleaseCallback();
|
||||
|
||||
native void HIDDeviceConnected(int deviceID, String identifier, int vendorId, int productId, String serial_number, int release_number, String manufacturer_string, String product_string, int interface_number, int interface_class, int interface_subclass, int interface_protocol, boolean bBluetooth, int reportID);
|
||||
native void HIDDeviceOpenPending(int deviceID);
|
||||
native void HIDDeviceOpenResult(int deviceID, boolean opened);
|
||||
native void HIDDeviceDisconnected(int deviceID);
|
||||
|
||||
native void HIDDeviceInputReport(int deviceID, byte[] report);
|
||||
native void HIDDeviceReportResponse(int deviceID, byte[] report);
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.hardware.usb.*;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
|
||||
class HIDDeviceUSB implements HIDDevice {
|
||||
|
||||
private static final String TAG = "hidapi";
|
||||
|
||||
protected HIDDeviceManager mManager;
|
||||
protected UsbDevice mDevice;
|
||||
protected int mInterfaceIndex;
|
||||
protected int mInterface;
|
||||
protected int mDeviceId;
|
||||
protected UsbDeviceConnection mConnection;
|
||||
protected UsbEndpoint mInputEndpoint;
|
||||
protected UsbEndpoint mOutputEndpoint;
|
||||
protected InputThread mInputThread;
|
||||
protected boolean mRunning;
|
||||
protected boolean mFrozen;
|
||||
protected boolean mClaimed;
|
||||
|
||||
public HIDDeviceUSB(HIDDeviceManager manager, UsbDevice usbDevice, int interface_index) {
|
||||
mManager = manager;
|
||||
mDevice = usbDevice;
|
||||
mInterfaceIndex = interface_index;
|
||||
mInterface = mDevice.getInterface(mInterfaceIndex).getId();
|
||||
mDeviceId = manager.getDeviceIDForIdentifier(getIdentifier());
|
||||
mRunning = false;
|
||||
mClaimed = false;
|
||||
}
|
||||
|
||||
String getIdentifier() {
|
||||
return String.format(Locale.ENGLISH, "%s/%x/%x/%d", mDevice.getDeviceName(), mDevice.getVendorId(), mDevice.getProductId(), mInterfaceIndex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getId() {
|
||||
return mDeviceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getVendorId() {
|
||||
return mDevice.getVendorId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getProductId() {
|
||||
return mDevice.getProductId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSerialNumber() {
|
||||
String result = null;
|
||||
try {
|
||||
result = mDevice.getSerialNumber();
|
||||
}
|
||||
catch (Exception exception) {
|
||||
//Log.w(TAG, "App permissions mean we cannot get serial number for device " + getDeviceName() + " message: " + exception.getMessage());
|
||||
}
|
||||
if (result == null) {
|
||||
result = "";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getVersion() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getManufacturerName() {
|
||||
String result;
|
||||
result = mDevice.getManufacturerName();
|
||||
if (result == null) {
|
||||
result = String.format("%x", getVendorId());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getProductName() {
|
||||
String result;
|
||||
result = mDevice.getProductName();
|
||||
if (result == null) {
|
||||
result = String.format("%x", getProductId());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UsbDevice getDevice() {
|
||||
return mDevice;
|
||||
}
|
||||
|
||||
String getDeviceName() {
|
||||
return getManufacturerName() + " " + getProductName() + "(0x" + String.format("%x", getVendorId()) + "/0x" + String.format("%x", getProductId()) + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean open() {
|
||||
mConnection = mManager.getUSBManager().openDevice(mDevice);
|
||||
if (mConnection == null) {
|
||||
Log.w(TAG, "Unable to open USB device " + getDeviceName());
|
||||
return false;
|
||||
}
|
||||
|
||||
// Force claim our interface
|
||||
UsbInterface iface = mDevice.getInterface(mInterfaceIndex);
|
||||
if (!mConnection.claimInterface(iface, true)) {
|
||||
Log.w(TAG, "Failed to claim interfaces on USB device " + getDeviceName());
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
mClaimed = true;
|
||||
|
||||
// Find the endpoints
|
||||
for (int j = 0; j < iface.getEndpointCount(); j++) {
|
||||
UsbEndpoint endpt = iface.getEndpoint(j);
|
||||
switch (endpt.getDirection()) {
|
||||
case UsbConstants.USB_DIR_IN:
|
||||
if (mInputEndpoint == null) {
|
||||
mInputEndpoint = endpt;
|
||||
}
|
||||
break;
|
||||
case UsbConstants.USB_DIR_OUT:
|
||||
if (mOutputEndpoint == null) {
|
||||
mOutputEndpoint = endpt;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure the required endpoints were present. The original Steam Controller and the wireless dongle for it do NOT
|
||||
// actually have -- or require -- output endpoints, so we need to accept only an input one for them or else we'll fall
|
||||
// back to the Android system gamepad functionality (and lose our paddles et al).
|
||||
if (mInputEndpoint == null) {
|
||||
Log.w(TAG, "Missing required endpoint on USB device " + getDeviceName());
|
||||
mConnection.releaseInterface(iface);
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Start listening for input
|
||||
mRunning = true;
|
||||
mInputThread = new InputThread();
|
||||
mInputThread.start();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int writeReport(byte[] report, boolean feature) {
|
||||
if (mConnection == null) {
|
||||
Log.w(TAG, "writeReport() called with no device connection");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!mClaimed) {
|
||||
Log.w(TAG, "writeReport() called but some other process currently owns the USB device");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (feature) {
|
||||
int res = -1;
|
||||
int offset = 0;
|
||||
int length = report.length;
|
||||
boolean skipped_report_id = false;
|
||||
byte report_number = report[0];
|
||||
|
||||
if (report_number == 0x0) {
|
||||
++offset;
|
||||
--length;
|
||||
skipped_report_id = true;
|
||||
}
|
||||
|
||||
res = mConnection.controlTransfer(
|
||||
UsbConstants.USB_TYPE_CLASS | 0x01 /*RECIPIENT_INTERFACE*/ | UsbConstants.USB_DIR_OUT,
|
||||
0x09/*HID set_report*/,
|
||||
(3/*HID feature*/ << 8) | report_number,
|
||||
mInterface,
|
||||
report, offset, length,
|
||||
1000/*timeout millis*/);
|
||||
|
||||
if (res < 0) {
|
||||
Log.w(TAG, "writeFeatureReport() returned " + res + " on device " + getDeviceName());
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (skipped_report_id) {
|
||||
++length;
|
||||
}
|
||||
return length;
|
||||
} else {
|
||||
if (mOutputEndpoint == null)
|
||||
{
|
||||
Log.e(TAG, "Tried to write an output report to an interface with no output endpoint!");
|
||||
return -1;
|
||||
}
|
||||
int res = mConnection.bulkTransfer(mOutputEndpoint, report, report.length, 1000);
|
||||
if (res != report.length) {
|
||||
Log.w(TAG, "writeOutputReport() returned " + res + " on device " + getDeviceName());
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean readReport(byte[] report, boolean feature) {
|
||||
int res = -1;
|
||||
int offset = 0;
|
||||
int length = report.length;
|
||||
boolean skipped_report_id = false;
|
||||
byte report_number = report[0];
|
||||
|
||||
if (mConnection == null) {
|
||||
Log.w(TAG, "readReport() called with no device connection");
|
||||
return false;
|
||||
}
|
||||
if (!mClaimed) {
|
||||
if (feature) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (report_number == 0x0) {
|
||||
/* Offset the return buffer by 1, so that the report ID
|
||||
will remain in byte 0. */
|
||||
++offset;
|
||||
--length;
|
||||
skipped_report_id = true;
|
||||
}
|
||||
|
||||
res = mConnection.controlTransfer(
|
||||
UsbConstants.USB_TYPE_CLASS | 0x01 /*RECIPIENT_INTERFACE*/ | UsbConstants.USB_DIR_IN,
|
||||
0x01/*HID get_report*/,
|
||||
((feature ? 3/*HID feature*/ : 1/*HID Input*/) << 8) | report_number,
|
||||
mInterface,
|
||||
report, offset, length,
|
||||
1000/*timeout millis*/);
|
||||
|
||||
if (res < 0) {
|
||||
Log.w(TAG, "getFeatureReport() returned " + res + " on device " + getDeviceName());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (skipped_report_id) {
|
||||
++res;
|
||||
++length;
|
||||
}
|
||||
|
||||
byte[] data;
|
||||
if (res == length) {
|
||||
data = report;
|
||||
} else {
|
||||
data = Arrays.copyOfRange(report, 0, res);
|
||||
}
|
||||
mManager.HIDDeviceReportResponse(mDeviceId, data);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
mRunning = false;
|
||||
if (mInputThread != null) {
|
||||
while (mInputThread.isAlive()) {
|
||||
mInputThread.interrupt();
|
||||
try {
|
||||
mInputThread.join();
|
||||
} catch (InterruptedException e) {
|
||||
// Keep trying until we're done
|
||||
}
|
||||
}
|
||||
mInputThread = null;
|
||||
}
|
||||
if (mConnection != null) {
|
||||
if (mClaimed) {
|
||||
UsbInterface iface = mDevice.getInterface(mInterfaceIndex);
|
||||
mConnection.releaseInterface(iface);
|
||||
}
|
||||
mConnection.close();
|
||||
mConnection = null;
|
||||
mClaimed = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
close();
|
||||
mManager = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFrozen(boolean frozen) {
|
||||
mFrozen = frozen;
|
||||
|
||||
/* If we have a valid device connection and the claim state doesn't match what we want, try to correct that. */
|
||||
if (mConnection != null && mClaimed == mFrozen) {
|
||||
UsbInterface iface = mDevice.getInterface(mInterfaceIndex);
|
||||
if (frozen) {
|
||||
mClaimed = !mConnection.releaseInterface(iface);
|
||||
if (mClaimed) {
|
||||
Log.e(TAG, "Tried to release claim on USB device, but failed!");
|
||||
}
|
||||
} else {
|
||||
mClaimed = mConnection.claimInterface(iface, true);
|
||||
if (!mClaimed) {
|
||||
Log.e(TAG, "Tried to regain claim on USB device, but failed!");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected class InputThread extends Thread {
|
||||
@Override
|
||||
public void run() {
|
||||
int packetSize = mInputEndpoint.getMaxPacketSize();
|
||||
byte[] packet = new byte[packetSize];
|
||||
while (mRunning) {
|
||||
int r;
|
||||
try
|
||||
{
|
||||
r = mConnection.bulkTransfer(mInputEndpoint, packet, packetSize, 1000);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.v(TAG, "Exception in UsbDeviceConnection bulktransfer: " + e);
|
||||
break;
|
||||
}
|
||||
if (r < 0) {
|
||||
// Could be a timeout or an I/O error
|
||||
}
|
||||
if (r > 0) {
|
||||
byte[] data;
|
||||
if (r == packetSize) {
|
||||
data = packet;
|
||||
} else {
|
||||
data = Arrays.copyOfRange(packet, 0, r);
|
||||
}
|
||||
|
||||
if (!mFrozen) {
|
||||
mManager.HIDDeviceInputReport(mDeviceId, data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
SDL library initialization
|
||||
*/
|
||||
public class SDL {
|
||||
|
||||
// This function should be called first and sets up the native code
|
||||
// so it can call into the Java classes
|
||||
static public void setupJNI() {
|
||||
SDLActivity.nativeSetupJNI();
|
||||
SDLAudioManager.nativeSetupJNI();
|
||||
SDLControllerManager.nativeSetupJNI();
|
||||
}
|
||||
|
||||
// This function should be called each time the activity is started
|
||||
static public void initialize() {
|
||||
setContext(null);
|
||||
|
||||
SDLActivity.initialize();
|
||||
SDLAudioManager.initialize();
|
||||
SDLControllerManager.initialize();
|
||||
}
|
||||
|
||||
// This function stores the current activity (SDL or not)
|
||||
static public void setContext(Activity context) {
|
||||
SDLAudioManager.setContext(context);
|
||||
mContext = context;
|
||||
}
|
||||
|
||||
static public Activity getContext() {
|
||||
return mContext;
|
||||
}
|
||||
|
||||
static void loadLibrary(String libraryName) throws UnsatisfiedLinkError, SecurityException, NullPointerException {
|
||||
loadLibrary(libraryName, mContext);
|
||||
}
|
||||
|
||||
static void loadLibrary(String libraryName, Context context) throws UnsatisfiedLinkError, SecurityException, NullPointerException {
|
||||
|
||||
if (libraryName == null) {
|
||||
throw new NullPointerException("No library name provided.");
|
||||
}
|
||||
|
||||
try {
|
||||
// Let's see if we have ReLinker available in the project. This is necessary for
|
||||
// some projects that have huge numbers of local libraries bundled, and thus may
|
||||
// trip a bug in Android's native library loader which ReLinker works around. (If
|
||||
// loadLibrary works properly, ReLinker will simply use the normal Android method
|
||||
// internally.)
|
||||
//
|
||||
// To use ReLinker, just add it as a dependency. For more information, see
|
||||
// https://github.com/KeepSafe/ReLinker for ReLinker's repository.
|
||||
//
|
||||
Class<?> relinkClass = context.getClassLoader().loadClass("com.getkeepsafe.relinker.ReLinker");
|
||||
Class<?> relinkListenerClass = context.getClassLoader().loadClass("com.getkeepsafe.relinker.ReLinker$LoadListener");
|
||||
Class<?> contextClass = context.getClassLoader().loadClass("android.content.Context");
|
||||
Class<?> stringClass = context.getClassLoader().loadClass("java.lang.String");
|
||||
|
||||
// Get a 'force' instance of the ReLinker, so we can ensure libraries are reinstalled if
|
||||
// they've changed during updates.
|
||||
Method forceMethod = relinkClass.getDeclaredMethod("force");
|
||||
Object relinkInstance = forceMethod.invoke(null);
|
||||
Class<?> relinkInstanceClass = relinkInstance.getClass();
|
||||
|
||||
// Actually load the library!
|
||||
Method loadMethod = relinkInstanceClass.getDeclaredMethod("loadLibrary", contextClass, stringClass, stringClass, relinkListenerClass);
|
||||
loadMethod.invoke(relinkInstance, context, libraryName, null, null);
|
||||
}
|
||||
catch (final Throwable e) {
|
||||
// Fall back
|
||||
try {
|
||||
System.loadLibrary(libraryName);
|
||||
}
|
||||
catch (final UnsatisfiedLinkError ule) {
|
||||
throw ule;
|
||||
}
|
||||
catch (final SecurityException se) {
|
||||
throw se;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected static Activity mContext;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,126 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.content.Context;
|
||||
import android.media.AudioDeviceCallback;
|
||||
import android.media.AudioDeviceInfo;
|
||||
import android.media.AudioManager;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.ArrayList;
|
||||
|
||||
class SDLAudioManager {
|
||||
protected static final String TAG = "SDLAudio";
|
||||
|
||||
protected static Context mContext;
|
||||
|
||||
private static AudioDeviceCallback mAudioDeviceCallback;
|
||||
|
||||
static void initialize() {
|
||||
mAudioDeviceCallback = null;
|
||||
|
||||
if(Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */)
|
||||
{
|
||||
mAudioDeviceCallback = new AudioDeviceCallback() {
|
||||
@Override
|
||||
public void onAudioDevicesAdded(AudioDeviceInfo[] addedDevices) {
|
||||
for (AudioDeviceInfo deviceInfo : addedDevices) {
|
||||
nativeAddAudioDevice(deviceInfo.isSink(), deviceInfo.getProductName().toString(), deviceInfo.getId());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAudioDevicesRemoved(AudioDeviceInfo[] removedDevices) {
|
||||
for (AudioDeviceInfo deviceInfo : removedDevices) {
|
||||
nativeRemoveAudioDevice(deviceInfo.isSink(), deviceInfo.getId());
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
static void setContext(Context context) {
|
||||
mContext = context;
|
||||
}
|
||||
|
||||
static void release(Context context) {
|
||||
// no-op atm
|
||||
}
|
||||
|
||||
// Audio
|
||||
|
||||
private static AudioDeviceInfo getInputAudioDeviceInfo(int deviceId) {
|
||||
if (Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */) {
|
||||
AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
|
||||
for (AudioDeviceInfo deviceInfo : audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS)) {
|
||||
if (deviceInfo.getId() == deviceId) {
|
||||
return deviceInfo;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static AudioDeviceInfo getPlaybackAudioDeviceInfo(int deviceId) {
|
||||
if (Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */) {
|
||||
AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
|
||||
for (AudioDeviceInfo deviceInfo : audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS)) {
|
||||
if (deviceInfo.getId() == deviceId) {
|
||||
return deviceInfo;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static void registerAudioDeviceCallback() {
|
||||
if (Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */) {
|
||||
AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
|
||||
// get an initial list now, before hotplug callbacks fire.
|
||||
for (AudioDeviceInfo dev : audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS)) {
|
||||
if (dev.getType() == AudioDeviceInfo.TYPE_TELEPHONY) {
|
||||
continue; // Device cannot be opened
|
||||
}
|
||||
nativeAddAudioDevice(dev.isSink(), dev.getProductName().toString(), dev.getId());
|
||||
}
|
||||
for (AudioDeviceInfo dev : audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS)) {
|
||||
nativeAddAudioDevice(dev.isSink(), dev.getProductName().toString(), dev.getId());
|
||||
}
|
||||
audioManager.registerAudioDeviceCallback(mAudioDeviceCallback, null);
|
||||
}
|
||||
}
|
||||
|
||||
static void unregisterAudioDeviceCallback() {
|
||||
if (Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */) {
|
||||
AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
|
||||
audioManager.unregisterAudioDeviceCallback(mAudioDeviceCallback);
|
||||
}
|
||||
}
|
||||
|
||||
/** This method is called by SDL using JNI. */
|
||||
static void audioSetThreadPriority(boolean recording, int device_id) {
|
||||
try {
|
||||
|
||||
/* Set thread name */
|
||||
if (recording) {
|
||||
Thread.currentThread().setName("SDLAudioC" + device_id);
|
||||
} else {
|
||||
Thread.currentThread().setName("SDLAudioP" + device_id);
|
||||
}
|
||||
|
||||
/* Set thread priority */
|
||||
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO);
|
||||
|
||||
} catch (Exception e) {
|
||||
Log.v(TAG, "modify thread properties failed " + e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
static native void nativeSetupJNI();
|
||||
|
||||
static native void nativeRemoveAudioDevice(boolean recording, int deviceId);
|
||||
|
||||
static native void nativeAddAudioDevice(boolean recording, String name, int deviceId);
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,66 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.content.*;
|
||||
import android.text.InputType;
|
||||
import android.view.*;
|
||||
import android.view.inputmethod.EditorInfo;
|
||||
import android.view.inputmethod.InputConnection;
|
||||
|
||||
/* This is a fake invisible editor view that receives the input and defines the
|
||||
* pan&scan region
|
||||
*/
|
||||
public class SDLDummyEdit extends View implements View.OnKeyListener
|
||||
{
|
||||
InputConnection ic;
|
||||
int input_type;
|
||||
|
||||
SDLDummyEdit(Context context) {
|
||||
super(context);
|
||||
setFocusableInTouchMode(true);
|
||||
setFocusable(true);
|
||||
setOnKeyListener(this);
|
||||
}
|
||||
|
||||
void setInputType(int input_type) {
|
||||
this.input_type = input_type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCheckIsTextEditor() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onKey(View v, int keyCode, KeyEvent event) {
|
||||
return SDLActivity.handleKeyEvent(v, keyCode, event, ic);
|
||||
}
|
||||
|
||||
//
|
||||
@Override
|
||||
public boolean onKeyPreIme (int keyCode, KeyEvent event) {
|
||||
// As seen on StackOverflow: http://stackoverflow.com/questions/7634346/keyboard-hide-event
|
||||
// FIXME: Discussion at http://bugzilla.libsdl.org/show_bug.cgi?id=1639
|
||||
// FIXME: This is not a 100% effective solution to the problem of detecting if the keyboard is showing or not
|
||||
// FIXME: A more effective solution would be to assume our Layout to be RelativeLayout or LinearLayout
|
||||
// FIXME: And determine the keyboard presence doing this: http://stackoverflow.com/questions/2150078/how-to-check-visibility-of-software-keyboard-in-android
|
||||
// FIXME: An even more effective way would be if Android provided this out of the box, but where would the fun be in that :)
|
||||
if (event.getAction()==KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
|
||||
if (SDLActivity.mTextEdit != null && SDLActivity.mTextEdit.getVisibility() == View.VISIBLE) {
|
||||
SDLActivity.onNativeKeyboardFocusLost();
|
||||
}
|
||||
}
|
||||
return super.onKeyPreIme(keyCode, event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
|
||||
ic = new SDLInputConnection(this, true);
|
||||
|
||||
outAttrs.inputType = input_type;
|
||||
outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI |
|
||||
EditorInfo.IME_FLAG_NO_FULLSCREEN /* API 11 */;
|
||||
|
||||
return ic;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.content.*;
|
||||
import android.os.Build;
|
||||
import android.text.Editable;
|
||||
import android.view.*;
|
||||
import android.view.inputmethod.BaseInputConnection;
|
||||
import android.widget.EditText;
|
||||
|
||||
class SDLInputConnection extends BaseInputConnection
|
||||
{
|
||||
protected EditText mEditText;
|
||||
protected String mCommittedText = "";
|
||||
|
||||
SDLInputConnection(View targetView, boolean fullEditor) {
|
||||
super(targetView, fullEditor);
|
||||
mEditText = new EditText(SDL.getContext());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Editable getEditable() {
|
||||
return mEditText.getEditableText();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean sendKeyEvent(KeyEvent event) {
|
||||
/*
|
||||
* This used to handle the keycodes from soft keyboard (and IME-translated input from hardkeyboard)
|
||||
* However, as of Ice Cream Sandwich and later, almost all soft keyboard doesn't generate key presses
|
||||
* and so we need to generate them ourselves in commitText. To avoid duplicates on the handful of keys
|
||||
* that still do, we empty this out.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Return DOES still generate a key event, however. So rather than using it as the 'click a button' key
|
||||
* as we do with physical keyboards, let's just use it to hide the keyboard.
|
||||
*/
|
||||
|
||||
if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
|
||||
if (SDLActivity.onNativeSoftReturnKey()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return super.sendKeyEvent(event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean commitText(CharSequence text, int newCursorPosition) {
|
||||
if (!super.commitText(text, newCursorPosition)) {
|
||||
return false;
|
||||
}
|
||||
updateText();
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean setComposingText(CharSequence text, int newCursorPosition) {
|
||||
if (!super.setComposingText(text, newCursorPosition)) {
|
||||
return false;
|
||||
}
|
||||
updateText();
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteSurroundingText(int beforeLength, int afterLength) {
|
||||
// Workaround to capture backspace key. Ref: http://stackoverflow.com/questions>/14560344/android-backspace-in-webview-baseinputconnection
|
||||
// and https://bugzilla.libsdl.org/show_bug.cgi?id=2265
|
||||
if (beforeLength > 0 && afterLength == 0) {
|
||||
// backspace(s)
|
||||
while (beforeLength-- > 0) {
|
||||
nativeGenerateScancodeForUnichar('\b');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!super.deleteSurroundingText(beforeLength, afterLength)) {
|
||||
return false;
|
||||
}
|
||||
updateText();
|
||||
return true;
|
||||
}
|
||||
|
||||
protected void updateText() {
|
||||
final Editable content = getEditable();
|
||||
if (content == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String text = content.toString();
|
||||
int compareLength = Math.min(text.length(), mCommittedText.length());
|
||||
int matchLength, offset;
|
||||
|
||||
/* Backspace over characters that are no longer in the string */
|
||||
for (matchLength = 0; matchLength < compareLength; ) {
|
||||
int codePoint = mCommittedText.codePointAt(matchLength);
|
||||
if (codePoint != text.codePointAt(matchLength)) {
|
||||
break;
|
||||
}
|
||||
matchLength += Character.charCount(codePoint);
|
||||
}
|
||||
/* FIXME: This doesn't handle graphemes, like '🌬️' */
|
||||
for (offset = matchLength; offset < mCommittedText.length(); ) {
|
||||
int codePoint = mCommittedText.codePointAt(offset);
|
||||
nativeGenerateScancodeForUnichar('\b');
|
||||
offset += Character.charCount(codePoint);
|
||||
}
|
||||
|
||||
if (matchLength < text.length()) {
|
||||
String pendingText = text.subSequence(matchLength, text.length()).toString();
|
||||
if (!SDLActivity.dispatchingKeyEvent()) {
|
||||
for (offset = 0; offset < pendingText.length(); ) {
|
||||
int codePoint = pendingText.codePointAt(offset);
|
||||
if (codePoint == '\n') {
|
||||
if (SDLActivity.onNativeSoftReturnKey()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
/* Higher code points don't generate simulated scancodes */
|
||||
if (codePoint > 0 && codePoint < 128) {
|
||||
nativeGenerateScancodeForUnichar((char)codePoint);
|
||||
}
|
||||
offset += Character.charCount(codePoint);
|
||||
}
|
||||
}
|
||||
SDLInputConnection.nativeCommitText(pendingText, 0);
|
||||
}
|
||||
mCommittedText = text;
|
||||
}
|
||||
|
||||
public static native void nativeCommitText(String text, int newCursorPosition);
|
||||
|
||||
public static native void nativeGenerateScancodeForUnichar(char c);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
import android.hardware.Sensor;
|
||||
import android.hardware.SensorEventListener;
|
||||
import android.hardware.SensorManager;
|
||||
import android.util.Log;
|
||||
|
||||
// This class coordinates synchronized access to sensor manager registration
|
||||
//
|
||||
// This prevents a java.util.ConcurrentModificationException exception on
|
||||
// Android 16, specifically on the Samsung Tab S9 Ultra.
|
||||
|
||||
class SDLSensorManager
|
||||
{
|
||||
static private SDLSensorManager mManager = new SDLSensorManager();
|
||||
|
||||
static final int RETRY_COUNT = 3;
|
||||
|
||||
public static void registerListener(SensorManager manager, SensorEventListener listener, Sensor sensor, int samplingPeriodUs) {
|
||||
mManager.RegisterListener(manager, listener, sensor, samplingPeriodUs);
|
||||
}
|
||||
|
||||
public static void unregisterListener(SensorManager manager, SensorEventListener listener, Sensor sensor) {
|
||||
mManager.UnregisterListener(manager, listener, sensor);
|
||||
}
|
||||
|
||||
private synchronized void RegisterListener(SensorManager manager, SensorEventListener listener, Sensor sensor, int samplingPeriodUs) {
|
||||
int retries = 0;
|
||||
boolean complete = false;
|
||||
while (!complete) {
|
||||
try {
|
||||
manager.registerListener(listener, sensor, samplingPeriodUs, null);
|
||||
complete = true;
|
||||
} catch (java.util.ConcurrentModificationException e) {
|
||||
++retries;
|
||||
if (retries <= RETRY_COUNT) {
|
||||
// Sleep a bit and try again
|
||||
try {
|
||||
Thread.sleep(1);
|
||||
} catch (Exception e2) {
|
||||
}
|
||||
} else {
|
||||
Log.v("SDL", "Multiple ConcurrentModificationException caught while registering sensor listener, canceling operation");
|
||||
complete = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void UnregisterListener(SensorManager manager, SensorEventListener listener, Sensor sensor) {
|
||||
int retries = 0;
|
||||
boolean complete = false;
|
||||
while (!complete) {
|
||||
try {
|
||||
manager.unregisterListener(listener, sensor);
|
||||
complete = true;
|
||||
} catch (java.util.ConcurrentModificationException e) {
|
||||
++retries;
|
||||
if (retries <= RETRY_COUNT) {
|
||||
// Sleep a bit and try again
|
||||
try {
|
||||
Thread.sleep(1);
|
||||
} catch (Exception e2) {
|
||||
}
|
||||
} else {
|
||||
Log.v("SDL", "Multiple ConcurrentModificationException caught while unregistering sensor listener, canceling operation");
|
||||
complete = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
package org.libsdl.app;
|
||||
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.pm.ActivityInfo;
|
||||
import android.graphics.Insets;
|
||||
import android.hardware.Sensor;
|
||||
import android.hardware.SensorEvent;
|
||||
import android.hardware.SensorEventListener;
|
||||
import android.hardware.SensorManager;
|
||||
import android.os.Build;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.util.Log;
|
||||
import android.view.Display;
|
||||
import android.view.InputDevice;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.PointerIcon;
|
||||
import android.view.Surface;
|
||||
import android.view.SurfaceHolder;
|
||||
import android.view.SurfaceView;
|
||||
import android.view.View;
|
||||
import android.view.WindowInsets;
|
||||
import android.view.WindowManager;
|
||||
|
||||
import android.view.ScaleGestureDetector;
|
||||
|
||||
/**
|
||||
SDLSurface. This is what we draw on, so we need to know when it's created
|
||||
in order to do anything useful.
|
||||
|
||||
Because of this, that's where we set up the SDL thread
|
||||
*/
|
||||
public class SDLSurface extends SurfaceView implements SurfaceHolder.Callback,
|
||||
View.OnApplyWindowInsetsListener, View.OnKeyListener, View.OnTouchListener,
|
||||
SensorEventListener, ScaleGestureDetector.OnScaleGestureListener {
|
||||
|
||||
// Sensors
|
||||
protected SensorManager mSensorManager;
|
||||
protected Display mDisplay;
|
||||
|
||||
// Keep track of the surface size to normalize touch events
|
||||
protected float mWidth, mHeight;
|
||||
|
||||
// Is SurfaceView ready for rendering
|
||||
protected boolean mIsSurfaceReady;
|
||||
|
||||
// Is on-screen keyboard visible
|
||||
protected boolean mKeyboardVisible;
|
||||
|
||||
// Pinch events
|
||||
private final ScaleGestureDetector scaleGestureDetector;
|
||||
|
||||
// Startup
|
||||
protected SDLSurface(Context context) {
|
||||
super(context);
|
||||
getHolder().addCallback(this);
|
||||
|
||||
scaleGestureDetector = new ScaleGestureDetector(context, this);
|
||||
|
||||
setFocusable(true);
|
||||
setFocusableInTouchMode(true);
|
||||
requestFocus();
|
||||
setOnApplyWindowInsetsListener(this);
|
||||
setOnKeyListener(this);
|
||||
setOnTouchListener(this);
|
||||
|
||||
mDisplay = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
|
||||
mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
|
||||
|
||||
setOnGenericMotionListener(SDLActivity.getMotionListener());
|
||||
|
||||
// Some arbitrary defaults to avoid a potential division by zero
|
||||
mWidth = 1.0f;
|
||||
mHeight = 1.0f;
|
||||
|
||||
mIsSurfaceReady = false;
|
||||
}
|
||||
|
||||
protected void handlePause() {
|
||||
enableSensor(Sensor.TYPE_ACCELEROMETER, false);
|
||||
}
|
||||
|
||||
protected void handleResume() {
|
||||
setFocusable(true);
|
||||
setFocusableInTouchMode(true);
|
||||
requestFocus();
|
||||
setOnApplyWindowInsetsListener(this);
|
||||
setOnKeyListener(this);
|
||||
setOnTouchListener(this);
|
||||
enableSensor(Sensor.TYPE_ACCELEROMETER, true);
|
||||
}
|
||||
|
||||
protected Surface getNativeSurface() {
|
||||
return getHolder().getSurface();
|
||||
}
|
||||
|
||||
// Called when we have a valid drawing surface
|
||||
@Override
|
||||
public void surfaceCreated(SurfaceHolder holder) {
|
||||
Log.v("SDL", "surfaceCreated()");
|
||||
SDLActivity.onNativeSurfaceCreated();
|
||||
}
|
||||
|
||||
// Called when we lose the surface
|
||||
@Override
|
||||
public void surfaceDestroyed(SurfaceHolder holder) {
|
||||
Log.v("SDL", "surfaceDestroyed()");
|
||||
|
||||
// Transition to pause, if needed
|
||||
SDLActivity.mNextNativeState = SDLActivity.NativeState.PAUSED;
|
||||
SDLActivity.handleNativeState();
|
||||
|
||||
mIsSurfaceReady = false;
|
||||
SDLActivity.onNativeSurfaceDestroyed();
|
||||
}
|
||||
|
||||
// Called when the surface is resized
|
||||
@Override
|
||||
public void surfaceChanged(SurfaceHolder holder,
|
||||
int format, int width, int height) {
|
||||
Log.v("SDL", "surfaceChanged()");
|
||||
|
||||
if (SDLActivity.mSingleton == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
mWidth = width;
|
||||
mHeight = height;
|
||||
int nDeviceWidth = width;
|
||||
int nDeviceHeight = height;
|
||||
float density = 1.0f;
|
||||
try
|
||||
{
|
||||
DisplayMetrics realMetrics = new DisplayMetrics();
|
||||
mDisplay.getRealMetrics( realMetrics );
|
||||
nDeviceWidth = realMetrics.widthPixels;
|
||||
nDeviceHeight = realMetrics.heightPixels;
|
||||
// Use densityDpi instead of density to more closely match what the UI scale is
|
||||
density = (float)realMetrics.densityDpi / 160.0f;
|
||||
} catch(Exception ignored) {
|
||||
}
|
||||
|
||||
synchronized(SDLActivity.getContext()) {
|
||||
// In case we're waiting on a size change after going fullscreen, send a notification.
|
||||
SDLActivity.getContext().notifyAll();
|
||||
}
|
||||
|
||||
Log.v("SDL", "Window size: " + width + "x" + height);
|
||||
Log.v("SDL", "Device size: " + nDeviceWidth + "x" + nDeviceHeight);
|
||||
SDLActivity.nativeSetScreenResolution(width, height, nDeviceWidth, nDeviceHeight, density, mDisplay.getRefreshRate());
|
||||
SDLActivity.onNativeResize();
|
||||
|
||||
// Prevent a screen distortion glitch,
|
||||
// for instance when the device is in Landscape and a Portrait App is resumed.
|
||||
boolean skip = false;
|
||||
int requestedOrientation = SDLActivity.mSingleton.getRequestedOrientation();
|
||||
|
||||
if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
|
||||
if (mWidth > mHeight) {
|
||||
skip = true;
|
||||
}
|
||||
} else if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE || requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
|
||||
if (mWidth < mHeight) {
|
||||
skip = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Special Patch for Square Resolution: Black Berry Passport
|
||||
if (skip) {
|
||||
double min = Math.min(mWidth, mHeight);
|
||||
double max = Math.max(mWidth, mHeight);
|
||||
|
||||
if (max / min < 1.20) {
|
||||
Log.v("SDL", "Don't skip on such aspect-ratio. Could be a square resolution.");
|
||||
skip = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Don't skip if we might be multi-window or have popup dialogs
|
||||
if (skip) {
|
||||
if (Build.VERSION.SDK_INT >= 24 /* Android 7.0 (N) */) {
|
||||
skip = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (skip) {
|
||||
Log.v("SDL", "Skip .. Surface is not ready.");
|
||||
mIsSurfaceReady = false;
|
||||
return;
|
||||
}
|
||||
|
||||
/* If the surface has been previously destroyed by onNativeSurfaceDestroyed, recreate it here */
|
||||
SDLActivity.onNativeSurfaceChanged();
|
||||
|
||||
/* Surface is ready */
|
||||
mIsSurfaceReady = true;
|
||||
|
||||
SDLActivity.mNextNativeState = SDLActivity.NativeState.RESUMED;
|
||||
SDLActivity.handleNativeState();
|
||||
}
|
||||
|
||||
// Window inset
|
||||
@Override
|
||||
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
|
||||
if (Build.VERSION.SDK_INT >= 30 /* Android 11 (R) */) {
|
||||
Insets combined = insets.getInsets(WindowInsets.Type.systemBars() |
|
||||
WindowInsets.Type.systemGestures() |
|
||||
WindowInsets.Type.mandatorySystemGestures() |
|
||||
WindowInsets.Type.tappableElement() |
|
||||
WindowInsets.Type.displayCutout());
|
||||
|
||||
SDLActivity.onNativeInsetsChanged(combined.left, combined.right, combined.top, combined.bottom);
|
||||
|
||||
if (insets.isVisible(WindowInsets.Type.ime())) {
|
||||
if (!mKeyboardVisible) {
|
||||
mKeyboardVisible = true;
|
||||
SDLActivity.onNativeScreenKeyboardShown();
|
||||
}
|
||||
} else {
|
||||
if (mKeyboardVisible) {
|
||||
mKeyboardVisible = false;
|
||||
SDLActivity.onNativeScreenKeyboardHidden();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pass these to any child views in case they need them
|
||||
return insets;
|
||||
}
|
||||
|
||||
// Key events
|
||||
@Override
|
||||
public boolean onKey(View v, int keyCode, KeyEvent event) {
|
||||
return SDLActivity.handleKeyEvent(v, keyCode, event, null);
|
||||
}
|
||||
|
||||
private float getNormalizedX(float x)
|
||||
{
|
||||
if (mWidth <= 1) {
|
||||
return 0.5f;
|
||||
} else {
|
||||
return (x / (mWidth - 1));
|
||||
}
|
||||
}
|
||||
|
||||
private float getNormalizedY(float y)
|
||||
{
|
||||
if (mHeight <= 1) {
|
||||
return 0.5f;
|
||||
} else {
|
||||
return (y / (mHeight - 1));
|
||||
}
|
||||
}
|
||||
|
||||
// Touch events
|
||||
@Override
|
||||
public boolean onTouch(View v, MotionEvent event) {
|
||||
/* Ref: http://developer.android.com/training/gestures/multi.html */
|
||||
int touchDevId = event.getDeviceId();
|
||||
final int pointerCount = event.getPointerCount();
|
||||
int action = event.getActionMasked();
|
||||
int pointerId;
|
||||
int i = 0;
|
||||
float x,y,p;
|
||||
|
||||
if (action == MotionEvent.ACTION_POINTER_UP || action == MotionEvent.ACTION_POINTER_DOWN)
|
||||
i = event.getActionIndex();
|
||||
|
||||
do {
|
||||
int toolType = event.getToolType(i);
|
||||
|
||||
if (toolType == MotionEvent.TOOL_TYPE_MOUSE) {
|
||||
int buttonState = event.getButtonState();
|
||||
boolean relative = false;
|
||||
|
||||
// We need to check if we're in relative mouse mode and get the axis offset rather than the x/y values
|
||||
// if we are. We'll leverage our existing mouse motion listener
|
||||
SDLGenericMotionListener_API14 motionListener = SDLActivity.getMotionListener();
|
||||
x = motionListener.getEventX(event, i);
|
||||
y = motionListener.getEventY(event, i);
|
||||
relative = motionListener.inRelativeMode();
|
||||
|
||||
SDLActivity.onNativeMouse(buttonState, action, x, y, relative);
|
||||
} else if (toolType == MotionEvent.TOOL_TYPE_STYLUS || toolType == MotionEvent.TOOL_TYPE_ERASER) {
|
||||
pointerId = event.getPointerId(i);
|
||||
x = event.getX(i);
|
||||
y = event.getY(i);
|
||||
p = event.getPressure(i);
|
||||
if (p > 1.0f) {
|
||||
// may be larger than 1.0f on some devices
|
||||
// see the documentation of getPressure(i)
|
||||
p = 1.0f;
|
||||
}
|
||||
|
||||
// BUTTON_STYLUS_PRIMARY is 2^5, so shift by 4, and apply SDL_PEN_INPUT_DOWN/SDL_PEN_INPUT_ERASER_TIP
|
||||
int buttonState = (event.getButtonState() >> 4) | (1 << (toolType == MotionEvent.TOOL_TYPE_STYLUS ? 0 : 30));
|
||||
if ((event.getButtonState() & MotionEvent.BUTTON_TERTIARY) != 0) {
|
||||
buttonState |= 0x08;
|
||||
}
|
||||
|
||||
SDLActivity.onNativePen(pointerId, SDLActivity.getMotionListener().getPenDeviceType(event.getDevice()), buttonState, action, x, y, p);
|
||||
} else { // MotionEvent.TOOL_TYPE_FINGER or MotionEvent.TOOL_TYPE_UNKNOWN
|
||||
pointerId = event.getPointerId(i);
|
||||
x = getNormalizedX(event.getX(i));
|
||||
y = getNormalizedY(event.getY(i));
|
||||
p = event.getPressure(i);
|
||||
if (p > 1.0f) {
|
||||
// may be larger than 1.0f on some devices
|
||||
// see the documentation of getPressure(i)
|
||||
p = 1.0f;
|
||||
}
|
||||
|
||||
SDLActivity.onNativeTouch(touchDevId, pointerId, action, x, y, p);
|
||||
}
|
||||
|
||||
// Non-primary up/down
|
||||
if (action == MotionEvent.ACTION_POINTER_UP || action == MotionEvent.ACTION_POINTER_DOWN)
|
||||
break;
|
||||
} while (++i < pointerCount);
|
||||
|
||||
scaleGestureDetector.onTouchEvent(event);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Sensor events
|
||||
protected void enableSensor(int sensortype, boolean enabled) {
|
||||
// TODO: This uses getDefaultSensor - what if we have >1 accels?
|
||||
if (enabled) {
|
||||
SDLSensorManager.registerListener(mSensorManager, this,
|
||||
mSensorManager.getDefaultSensor(sensortype),
|
||||
SensorManager.SENSOR_DELAY_GAME);
|
||||
} else {
|
||||
SDLSensorManager.unregisterListener(mSensorManager, this,
|
||||
mSensorManager.getDefaultSensor(sensortype));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAccuracyChanged(Sensor sensor, int accuracy) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSensorChanged(SensorEvent event) {
|
||||
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
|
||||
|
||||
// Since we may have an orientation set, we won't receive onConfigurationChanged events.
|
||||
// We thus should check here.
|
||||
int newRotation;
|
||||
|
||||
float x, y;
|
||||
switch (mDisplay.getRotation()) {
|
||||
case Surface.ROTATION_0:
|
||||
default:
|
||||
x = event.values[0];
|
||||
y = event.values[1];
|
||||
newRotation = 0;
|
||||
break;
|
||||
case Surface.ROTATION_90:
|
||||
x = -event.values[1];
|
||||
y = event.values[0];
|
||||
newRotation = 90;
|
||||
break;
|
||||
case Surface.ROTATION_180:
|
||||
x = -event.values[0];
|
||||
y = -event.values[1];
|
||||
newRotation = 180;
|
||||
break;
|
||||
case Surface.ROTATION_270:
|
||||
x = event.values[1];
|
||||
y = -event.values[0];
|
||||
newRotation = 270;
|
||||
break;
|
||||
}
|
||||
|
||||
if (newRotation != SDLActivity.mCurrentRotation) {
|
||||
SDLActivity.mCurrentRotation = newRotation;
|
||||
SDLActivity.onNativeRotationChanged(newRotation);
|
||||
}
|
||||
|
||||
SDLActivity.onNativeAccel(-x / SensorManager.GRAVITY_EARTH,
|
||||
y / SensorManager.GRAVITY_EARTH,
|
||||
event.values[2] / SensorManager.GRAVITY_EARTH);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// Prevent android internal NullPointerException (https://github.com/libsdl-org/SDL/issues/13306)
|
||||
@Override
|
||||
public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
|
||||
try {
|
||||
return super.onResolvePointerIcon(event, pointerIndex);
|
||||
} catch (NullPointerException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Captured pointer events for API 26.
|
||||
@Override
|
||||
public boolean onCapturedPointerEvent(MotionEvent event)
|
||||
{
|
||||
return SDLActivity.getMotionListener().onGenericMotion(this, event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onScale(ScaleGestureDetector detector) {
|
||||
float scale = detector.getScaleFactor();
|
||||
SDLActivity.onNativePinchUpdate(scale);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onScaleBegin(ScaleGestureDetector detector) {
|
||||
SDLActivity.onNativePinchStart();
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScaleEnd(ScaleGestureDetector detector) {
|
||||
SDLActivity.onNativePinchEnd();
|
||||
}
|
||||
|
||||
}
|
||||
Vendored
+674
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
Pluvia is an unofficial Steam client app for Android
|
||||
Copyright (C) 2024 Oxters Wyzgowski
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
Pluvia Copyright (C) 2024 Oxters Wyzgowski
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,76 @@
|
||||
--- a/java/com/example/dsedge/BridgeActivity.java
|
||||
+++ b/java/com/example/dsedge/BridgeActivity.java
|
||||
@@ -174,7 +174,7 @@
|
||||
// ---- SDL3 driver ----
|
||||
LinearLayout drv = card(root);
|
||||
cardTitle(drv, "SDL3 driver");
|
||||
- addSpinner(drv, "Controller source", new String[] {
|
||||
+ if (!Host.embedded(this)) addSpinner(drv, "Controller source", new String[] {
|
||||
"Auto: any controller (SDL3 USB driver when plugged in, else Android/Bluetooth)",
|
||||
"Forced: only SDL3's USB driver (USB cable only)"
|
||||
}, Settings.forceUsb ? 1 : 0, v -> {
|
||||
--- a/java/com/example/dsedge/BridgeService.java
|
||||
+++ b/java/com/example/dsedge/BridgeService.java
|
||||
@@ -214,7 +214,7 @@
|
||||
: "SDL3Bridge · Steam Native Hook-up")
|
||||
.setContentText(text)
|
||||
.setStyle(new Notification.BigTextStyle().bigText(text))
|
||||
- .setSmallIcon(R.drawable.ic_stat_bridge)
|
||||
+ .setSmallIcon(com.droiddeck.launcher.R.drawable.sdl3_ic_stat_bridge)
|
||||
.setColor(0xFF4FC3F7)
|
||||
.setContentIntent(open)
|
||||
.setOngoing(true)
|
||||
@@ -832,6 +832,7 @@
|
||||
b.putInt("presentAs", Settings.presentAs);
|
||||
b.putBoolean("driverEnabled", Settings.driverEnabled);
|
||||
b.putBoolean("forceUsb", Settings.forceUsb);
|
||||
+ b.putBoolean("embedded", Host.embedded(this));
|
||||
b.putInt("pollMs", Settings.pollMs);
|
||||
b.putBoolean("bubble", Settings.bubble);
|
||||
// choices
|
||||
--- a/java/com/example/dsedge/Host.java
|
||||
+++ b/java/com/example/dsedge/Host.java
|
||||
@@ -16,6 +16,11 @@
|
||||
return c != null && !OWN_PACKAGE.equals(c.getPackageName());
|
||||
}
|
||||
|
||||
+ static boolean usbOnly(Context c, boolean configured) {
|
||||
+ // Android input events go to DroidDeck's activity, outside the headless SDL process.
|
||||
+ return embedded(c) || configured;
|
||||
+ }
|
||||
+
|
||||
/** A preferences file name of the bridge: unchanged as its own app, prefixed when built into another app. */
|
||||
static String prefs(Context c, String name) {
|
||||
return embedded(c) ? "sdl3bridge_" + name : name;
|
||||
--- a/java/com/example/dsedge/NativeBridge.java
|
||||
+++ b/java/com/example/dsedge/NativeBridge.java
|
||||
@@ -305,7 +305,7 @@
|
||||
|
||||
/** Forced mode: ignore Android's basic input and only use SDL's own USB driver. */
|
||||
static void applyForce() {
|
||||
- try { nativeSetForce(Settings.forceUsb ? 1 : 0); } catch (UnsatisfiedLinkError e) { }
|
||||
+ try { nativeSetForce(Host.usbOnly(appContext, Settings.forceUsb) ? 1 : 0); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static void rescan() {
|
||||
@@ -321,7 +321,7 @@
|
||||
try {
|
||||
nativeSetDriver(Settings.driverEnabled ? 1 : 0);
|
||||
nativeSetHookup(hookupMode());
|
||||
- if (Settings.driverEnabled) nativeSetForce(Settings.forceUsb ? 1 : 0);
|
||||
+ if (Settings.driverEnabled) nativeSetForce(Host.usbOnly(appContext, Settings.forceUsb) ? 1 : 0);
|
||||
} catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
--- a/native/main.c
|
||||
+++ b/native/main.c
|
||||
@@ -359,8 +359,7 @@
|
||||
SDL_free(ids);
|
||||
snprintf(diag, sizeof(diag),
|
||||
"Forced SDL3 USB mode: waiting for the USB driver. Plug the controller in with a USB-C cable, "
|
||||
- "then tap 'Force SDL3 USB driver' and allow USB access (or switch Controller source to Auto to "
|
||||
- "also use Bluetooth / Android-only controllers). Ignored Android-only controllers: %d", ignored);
|
||||
+ "then tap 'Force SDL3 USB driver' and allow USB access. Android-only controllers: %d", ignored);
|
||||
if (!atomic_load(&g_force))
|
||||
snprintf(diag, sizeof(diag), "Waiting for a controller: plug any SDL3-supported controller in via USB-C "
|
||||
"(full features) or connect it over Bluetooth");
|
||||
@@ -0,0 +1,74 @@
|
||||
--- a/native/main.c
|
||||
+++ b/native/main.c
|
||||
@@ -279,7 +279,7 @@
|
||||
SDL_free(ids);
|
||||
}
|
||||
|
||||
-static char g_last_diag[512];
|
||||
+static char g_last_diag[560];
|
||||
|
||||
/* In forced mode an Android-path gamepad (no SDL USB path) is never used. */
|
||||
static bool usable_id(SDL_JoystickID id)
|
||||
@@ -328,7 +328,7 @@
|
||||
|
||||
static void refresh_status(JNIEnv *env)
|
||||
{
|
||||
- char diag[560];
|
||||
+ char diag[sizeof(g_last_diag)];
|
||||
if (atomic_load(&g_driver_off)) {
|
||||
snprintf(diag, sizeof(diag), "SDL3 driver OFF \u2014 controller released to Android (tap the bubble to turn it back on)");
|
||||
} else if (g_pads[0]) {
|
||||
@@ -453,6 +453,10 @@
|
||||
g_pads[0] = g_pads[k];
|
||||
g_ids[0] = g_ids[k];
|
||||
g_pads[k] = NULL;
|
||||
+ SDL_RumbleGamepad(g_pads[0], 0, 0, 0);
|
||||
+ atomic_store(&g_rl[k], 0);
|
||||
+ atomic_store(&g_rr[k], 0);
|
||||
+ rumble_on[k] = 0;
|
||||
send_gone(env, k);
|
||||
setup_slot(env, 0);
|
||||
break;
|
||||
--- a/native/hookup.h
|
||||
+++ b/native/hookup.h
|
||||
@@ -211,6 +211,11 @@
|
||||
memset(&g_hk[i], 0, sizeof(g_hk[i]));
|
||||
atomic_store(&g_hk_gone[i], 0);
|
||||
atomic_store(&g_hk_fast_now[i], 0);
|
||||
+ if (g_hks.base) {
|
||||
+ uint8_t *s = hks_slot(&g_hks, i);
|
||||
+ __atomic_store_n(hks_u32(s, HKS_PRESENT), 0, __ATOMIC_RELEASE);
|
||||
+ __atomic_store_n(hks_u64(s, HKS_DIRECT_MS), 0, __ATOMIC_RELEASE);
|
||||
+ }
|
||||
pthread_mutex_unlock(&g_hk_io);
|
||||
pthread_mutex_unlock(&g_hk_wr);
|
||||
g_hk_fast_logged[i] = 0;
|
||||
--- a/java/com/example/dsedge/BridgeActivity.java
|
||||
+++ b/java/com/example/dsedge/BridgeActivity.java
|
||||
@@ -290,7 +290,7 @@
|
||||
gc.addView(button("Reset calibration", v -> resetGyroCalibration()), weight());
|
||||
box.addView(gc);
|
||||
box.addView(gyroCalibView);
|
||||
- box.addView(sub("Calibration samples the controller shown above (player 1 slot). Deadzone ignores tiny drift.", 11f));
|
||||
+ box.addView(sub("Calibration samples the selected player. Deadzone ignores tiny drift.", 11f));
|
||||
|
||||
subhead(box, "Touchpad");
|
||||
addCheck(box, "Invert touchpad X (left/right)", Settings.touchInvX[p], on -> Settings.touchInvX[p] = on);
|
||||
@@ -718,8 +718,7 @@
|
||||
}
|
||||
|
||||
@Override public void onFrame(float[] f, int slot) {
|
||||
- if (slot != 0) return; // the test screen shows player 1
|
||||
- if (calibCount >= 0 && f.length >= 13) {
|
||||
+ if (slot == calibPlayer && calibCount >= 0 && f.length >= 13) {
|
||||
calibSum[0] += f[7]; calibSum[1] += f[8]; calibSum[2] += f[9];
|
||||
if (++calibCount >= CALIB_SAMPLES) {
|
||||
float[] b = Settings.gyroBias[calibPlayer];
|
||||
@@ -731,6 +730,7 @@
|
||||
ui.post(() -> { if (gyroCalibView != null && uiPlayer == calibPlayer) gyroCalibView.setText(calibLabel(calibPlayer)); });
|
||||
}
|
||||
}
|
||||
+ if (slot != 0) return; // the test screen shows player 1
|
||||
pad.update(f);
|
||||
long now = System.nanoTime();
|
||||
if (now - lastSummary > 300_000_000L) {
|
||||
@@ -0,0 +1,23 @@
|
||||
--- a/java/com/example/dsedge/BridgeActivity.java
|
||||
+++ b/java/com/example/dsedge/BridgeActivity.java
|
||||
@@ -454,12 +454,16 @@
|
||||
sb.setProgressTintList(ColorStateList.valueOf(ACCENT));
|
||||
sb.setThumbTintList(ColorStateList.valueOf(ACCENT));
|
||||
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
|
||||
+ private boolean tracking;
|
||||
@Override public void onProgressChanged(SeekBar s, int v, boolean fromUser) {
|
||||
t.setText(label + ": " + v);
|
||||
- if (fromUser) sink.set(v);
|
||||
- }
|
||||
- @Override public void onStartTrackingTouch(SeekBar s) { }
|
||||
- @Override public void onStopTrackingTouch(SeekBar s) { Settings.save(); }
|
||||
+ if (fromUser) {
|
||||
+ sink.set(v);
|
||||
+ if (!tracking) Settings.save();
|
||||
+ }
|
||||
+ }
|
||||
+ @Override public void onStartTrackingTouch(SeekBar s) { tracking = true; }
|
||||
+ @Override public void onStopTrackingTouch(SeekBar s) { tracking = false; Settings.save(); }
|
||||
});
|
||||
root.addView(t);
|
||||
root.addView(sb);
|
||||
Vendored
+76
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"version": 1,
|
||||
"source": {
|
||||
"repository": "https://github.com/pablo89898991/SdlBridge",
|
||||
"commit": "63feeac6a3b9f3b51ec7664d677e099cdf5ae4d0",
|
||||
"integration_repository": "https://github.com/pablo89898991/SDLApiDroidDeck",
|
||||
"integration_commit": "131f1ceffe52554758079c6a3bb3c045b9be2afe"
|
||||
},
|
||||
"files": {
|
||||
"java/com/example/dsedge/BridgeActivity.java": {
|
||||
"source": "app/src/main/java/com/example/dsedge/BridgeActivity.java",
|
||||
"sha256": "e56a7740e897c3a8e72c0aeb29b9cd78c6815fb4b1e177ff713cd28a477ba01c"
|
||||
},
|
||||
"java/com/example/dsedge/BridgeService.java": {
|
||||
"source": "app/src/main/java/com/example/dsedge/BridgeService.java",
|
||||
"sha256": "bc613763a8c3dbef26dc6ddde1cfafa2342391cc230795728a39058365e8f624"
|
||||
},
|
||||
"java/com/example/dsedge/ControllerView.java": {
|
||||
"source": "app/src/main/java/com/example/dsedge/ControllerView.java",
|
||||
"sha256": "4f7bd81223b4058853dd4380263a9e5f99679ba78f3627de87947f7753874fcf"
|
||||
},
|
||||
"java/com/example/dsedge/HookupIdentity.java": {
|
||||
"source": "app/src/main/java/com/example/dsedge/HookupIdentity.java",
|
||||
"sha256": "5179ef52f1b9c4319def2e3af250b0e63ed173c6bbbfc5dfde6ffedae947c9cd"
|
||||
},
|
||||
"java/com/example/dsedge/Host.java": {
|
||||
"source": "app/src/main/java/com/example/dsedge/Host.java",
|
||||
"sha256": "3fb04cb3275af97fec4c76e29d269ac5ed6c282cdcedb3fc249f6165e9ee75d5"
|
||||
},
|
||||
"java/com/example/dsedge/NativeBridge.java": {
|
||||
"source": "app/src/main/java/com/example/dsedge/NativeBridge.java",
|
||||
"sha256": "b3195c541d1f8a476da972f4b3fd5eb1acfa13540ebf516c1cbe4c713d5675b3"
|
||||
},
|
||||
"java/com/example/dsedge/SdlEngine.java": {
|
||||
"source": "app/src/main/java/com/example/dsedge/SdlEngine.java",
|
||||
"sha256": "777af8d6447f9be9cfef054ce016f61daaf6fe99334976c6a8657c58852dfef8"
|
||||
},
|
||||
"java/com/example/dsedge/SdlHostActivity.java": {
|
||||
"source": "app/src/main/java/com/example/dsedge/SdlHostActivity.java",
|
||||
"sha256": "39a1e8f01764ab5cecb0ffe90afd663a292648278dde180f6a0b4a5f35eb01f9"
|
||||
},
|
||||
"java/com/example/dsedge/Settings.java": {
|
||||
"source": "app/src/main/java/com/example/dsedge/Settings.java",
|
||||
"sha256": "65bcd3c9c0c1c2e485b9a14dd5de53505c3053c0bffa1684ae4a6023e66067ac"
|
||||
},
|
||||
"java/com/example/dsedge/UpdateChecker.java": {
|
||||
"source": "app/src/main/java/com/example/dsedge/UpdateChecker.java",
|
||||
"sha256": "f50cd1fbe6d93b74e8f77729c6850fcf0b156dfbc589d8f7725026dbfd296d37"
|
||||
},
|
||||
"java/com/example/dsedge/UsbAttachActivity.java": {
|
||||
"source": "app/src/main/java/com/example/dsedge/UsbAttachActivity.java",
|
||||
"sha256": "0c43ddf11ec8af80259c01359b3c2e920a4311b67d7a426d780f71bc0160e540"
|
||||
},
|
||||
"native/hkshm.h": {
|
||||
"source": "app/jni/src/hkshm.h",
|
||||
"sha256": "38f7f30a087f3ac3c7e0208744a338343e7d8940acd33c1386a3009a1f460df3"
|
||||
},
|
||||
"native/hookup.h": {
|
||||
"source": "app/jni/src/hookup.h",
|
||||
"sha256": "ec3aa73cfac6fecd1169ff91eccbbaf9a8deffc31a84bbb9ab198ea495946407"
|
||||
},
|
||||
"native/main.c": {
|
||||
"source": "app/jni/src/main.c",
|
||||
"sha256": "3bf05818ec786b76fcfc92e17f6e640a7473d74c8abc7acab2d863ca5bee92a6"
|
||||
},
|
||||
"native/triton.h": {
|
||||
"source": "app/jni/src/triton.h",
|
||||
"sha256": "1291e35392757b225cbebbb06e42649c1555fc1536b1b9ea804abaf2933adbde"
|
||||
}
|
||||
},
|
||||
"patches": [
|
||||
"patches/0001-droiddeck-integration.patch",
|
||||
"patches/0002-controller-state-fixes.patch",
|
||||
"patches/0003-persist-controller-settings.patch"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,765 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.app.PendingIntent;
|
||||
import android.content.Intent;
|
||||
import android.hardware.usb.UsbInterface;
|
||||
import android.os.Build;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Typeface;
|
||||
import android.graphics.drawable.GradientDrawable;
|
||||
import android.content.res.ColorStateList;
|
||||
import android.util.TypedValue;
|
||||
import android.hardware.usb.UsbDevice;
|
||||
import android.hardware.usb.UsbManager;
|
||||
import android.media.AudioDeviceInfo;
|
||||
import android.media.AudioManager;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.Button;
|
||||
import android.widget.CheckBox;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ScrollView;
|
||||
import android.widget.SeekBar;
|
||||
import android.widget.Spinner;
|
||||
import android.widget.TextView;
|
||||
|
||||
import org.libsdl.app.SDLControllerManager;
|
||||
|
||||
/**
|
||||
* The bridge's screen: live controller test and settings. SDL3 itself runs in the background service
|
||||
* (SdlEngine), so this screen can open and close at any time without affecting the controllers. (Fallback, if
|
||||
* SDL3 can't run in the background with this build: opening this screen starts SDL3 in a hidden screen behind it.)
|
||||
*/
|
||||
public class BridgeActivity extends android.app.Activity implements NativeBridge.Listener {
|
||||
private interface IntSink { void set(int v); }
|
||||
|
||||
private final Handler ui = new Handler(Looper.getMainLooper());
|
||||
private TextView statusView, summaryView, usbView;
|
||||
private Button updateButton;
|
||||
private ControllerView pad;
|
||||
private String updateUrl;
|
||||
private long lastSummary;
|
||||
private static final float RAD_TO_DEG = 57.29578f;
|
||||
private static final int CALIB_SAMPLES = 180; // ~0.7s at 4ms/frame
|
||||
private volatile int calibCount = -1; // -1 = not calibrating
|
||||
private final float[] calibSum = new float[3];
|
||||
private int calibPlayer = 0;
|
||||
private int uiPlayer = 0;
|
||||
private LinearLayout playerBox;
|
||||
private Button[] playerTabs;
|
||||
private TextView gyroCalibView;
|
||||
private boolean pendingBubble; // user asked for the bubble; waiting for overlay permission
|
||||
private TextView audioView;
|
||||
|
||||
|
||||
// ---- design tokens ----
|
||||
private static final int BG = 0xFF0E1116, CARD = 0xFF171C24, CARD2 = 0xFF222A35,
|
||||
ACCENT = 0xFF4FC3F7, TEXT = 0xFFECEFF1, SUB = 0xFF8A97A7,
|
||||
OKC = 0xFF34D399, WARNC = 0xFFF59E0B, BADC = 0xFFEF4444;
|
||||
private TextView statusPill;
|
||||
|
||||
private int dp(int v) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, v, getResources().getDisplayMetrics()); }
|
||||
|
||||
/** True while the bridge screen is open. */
|
||||
static volatile boolean running;
|
||||
|
||||
@Override protected void onCreate(Bundle state) {
|
||||
NativeBridge.appContext = getApplicationContext();
|
||||
running = true;
|
||||
super.onCreate(state);
|
||||
Settings.init(this);
|
||||
SdlEngine.start(this);
|
||||
// Android 13+: the status bar icon (the bridge's notification) needs this permission.
|
||||
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS)
|
||||
!= android.content.pm.PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(new String[] { android.Manifest.permission.POST_NOTIFICATIONS }, 1);
|
||||
}
|
||||
UpdateChecker.BuildInfo info = UpdateChecker.readBuildInfo(this);
|
||||
|
||||
LinearLayout root = new LinearLayout(this);
|
||||
root.setOrientation(LinearLayout.VERTICAL);
|
||||
root.setBackgroundColor(BG);
|
||||
root.setPadding(dp(14), dp(18), dp(14), dp(18));
|
||||
|
||||
// ---- header bar ----
|
||||
LinearLayout bar = new LinearLayout(this);
|
||||
bar.setOrientation(LinearLayout.HORIZONTAL);
|
||||
bar.setGravity(Gravity.CENTER_VERTICAL);
|
||||
LinearLayout titleCol = new LinearLayout(this);
|
||||
titleCol.setOrientation(LinearLayout.VERTICAL);
|
||||
TextView appTitle = new TextView(this);
|
||||
appTitle.setText("SDL3 Bridge");
|
||||
appTitle.setTextColor(TEXT);
|
||||
appTitle.setTextSize(21f);
|
||||
appTitle.setTypeface(Typeface.DEFAULT_BOLD);
|
||||
TextView appSub = new TextView(this);
|
||||
appSub.setText(info.tag + " · SDL " + info.sdl);
|
||||
appSub.setTextColor(SUB);
|
||||
appSub.setTextSize(11f);
|
||||
titleCol.addView(appTitle);
|
||||
titleCol.addView(appSub);
|
||||
bar.addView(titleCol, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
|
||||
statusPill = new TextView(this);
|
||||
statusPill.setText("Starting");
|
||||
statusPill.setTextColor(0xFF0E1116);
|
||||
statusPill.setTextSize(11f);
|
||||
statusPill.setTypeface(Typeface.DEFAULT_BOLD);
|
||||
statusPill.setPadding(dp(12), dp(6), dp(12), dp(6));
|
||||
statusPill.setBackground(pill(SUB));
|
||||
bar.addView(statusPill);
|
||||
root.addView(bar);
|
||||
spacer(root, 14);
|
||||
|
||||
// ---- controller test card ----
|
||||
LinearLayout test = card(root);
|
||||
statusView = sub(NativeBridge.lastStatus, 12f);
|
||||
usbView = sub("USB: checking...", 11f);
|
||||
pad = new ControllerView(this);
|
||||
test.addView(statusView);
|
||||
LinearLayout padWrap = new LinearLayout(this);
|
||||
padWrap.setBackground(rounded(0xFF0B0E13, dp(10)));
|
||||
padWrap.setPadding(dp(4), dp(4), dp(4), dp(4));
|
||||
padWrap.addView(pad, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
|
||||
LinearLayout.LayoutParams pw = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
pw.topMargin = dp(8); pw.bottomMargin = dp(8);
|
||||
test.addView(padWrap, pw);
|
||||
summaryView = sub("Press every button and move everything to test it.", 12f);
|
||||
test.addView(summaryView);
|
||||
test.addView(usbView);
|
||||
LinearLayout row = new LinearLayout(this);
|
||||
row.setOrientation(LinearLayout.HORIZONTAL);
|
||||
LinearLayout.LayoutParams rp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
rp.topMargin = dp(8);
|
||||
row.addView(primaryButton("Test rumble", v -> rumbleTest()), weight());
|
||||
gap(row);
|
||||
row.addView(button("Reset", v -> { pad.resetTested(); summaryView.setText(pad.summary()); }), weight());
|
||||
gap(row);
|
||||
updateButton = button("Update", v -> { if (updateUrl != null) openUrl(updateUrl); else checkUpdate(); });
|
||||
row.addView(updateButton, weight());
|
||||
test.addView(row, rp);
|
||||
|
||||
// ---- per-player settings ----
|
||||
LinearLayout playerCard = card(root);
|
||||
cardTitle(playerCard, "Player settings");
|
||||
LinearLayout tabs = new LinearLayout(this);
|
||||
tabs.setOrientation(LinearLayout.HORIZONTAL);
|
||||
tabs.setBackground(rounded(CARD2, dp(10)));
|
||||
tabs.setPadding(dp(4), dp(4), dp(4), dp(4));
|
||||
playerTabs = new Button[Settings.PLAYERS];
|
||||
for (int i = 0; i < Settings.PLAYERS; i++) {
|
||||
final int pi = i;
|
||||
Button t = new Button(this);
|
||||
t.setText("P" + (i + 1));
|
||||
t.setAllCaps(false);
|
||||
t.setTextSize(13f);
|
||||
t.setOnClickListener(v -> showPlayer(pi));
|
||||
playerTabs[i] = t;
|
||||
tabs.addView(t, weight());
|
||||
}
|
||||
playerCard.addView(tabs);
|
||||
playerBox = new LinearLayout(this);
|
||||
playerBox.setOrientation(LinearLayout.VERTICAL);
|
||||
LinearLayout.LayoutParams pbp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
pbp.topMargin = dp(10);
|
||||
playerCard.addView(playerBox, pbp);
|
||||
showPlayer(0);
|
||||
|
||||
// ---- SDL3 driver ----
|
||||
LinearLayout drv = card(root);
|
||||
cardTitle(drv, "SDL3 driver");
|
||||
addSpinner(drv, "Controller source", new String[] {
|
||||
"Auto: any controller (SDL3 USB driver when plugged in, else Android/Bluetooth)",
|
||||
"Forced: only SDL3's USB driver (USB cable only)"
|
||||
}, Settings.forceUsb ? 1 : 0, v -> {
|
||||
Settings.forceUsb = v == 1;
|
||||
Settings.save();
|
||||
NativeBridge.applyForce();
|
||||
});
|
||||
drv.addView(primaryButton("Force SDL3 USB driver", v -> forceUsbDriver()));
|
||||
drv.addView(sub("Plug the controller in with USB-C, tap the button and allow USB access "
|
||||
+ "(choose 'always' to skip this next time). Works for any SDL3-supported controller.", 11f));
|
||||
|
||||
// ---- Controller mode ----
|
||||
LinearLayout mode = card(root);
|
||||
cardTitle(mode, "Controller mode");
|
||||
addSpinner(mode, "Present controller as", Settings.PRESENT_NAMES, Settings.presentAs, v -> {
|
||||
Settings.presentAs = v;
|
||||
if (!Settings.isHookup()) Settings.lastPresentAs = v;
|
||||
Settings.save();
|
||||
NativeBridge.applyHookup();
|
||||
BridgeService.refreshBubble();
|
||||
});
|
||||
mode.addView(sub("Steam Deck: the controller is DroidDeck's Deck pad (default, full features). "
|
||||
+ "DualSense / DualShock 4: Steam sees a NATIVE Sony controller (hidraw) with gyro, touchpad and back buttons. "
|
||||
+ "Steam Native Hook-up: every USB controller is handed to Steam as itself (its real name and ids), "
|
||||
+ "so Steam's own driver gives it all its features, like on a PC; Bluetooth controllers stay a Deck pad. "
|
||||
+ "Give Steam a few seconds, or restart the session, after changing.", 11f));
|
||||
addSpinner(mode, "Poll rate", Settings.RATE_NAMES, rateIndex(), v -> {
|
||||
Settings.pollMs = Settings.RATE_MS[v];
|
||||
Settings.save();
|
||||
NativeBridge.applyRate();
|
||||
});
|
||||
mode.addView(sub("Higher rate = lower gyro/trackpad latency, a little more CPU and battery. No accuracy is lost either way.", 11f));
|
||||
|
||||
// ---- Floating bubble ----
|
||||
LinearLayout bub = card(root);
|
||||
cardTitle(bub, "Floating bubble");
|
||||
addCheck(bub, "Show floating bubble over other apps", Settings.bubble, on -> {
|
||||
if (on) {
|
||||
if (!android.provider.Settings.canDrawOverlays(this)) {
|
||||
pendingBubble = true;
|
||||
try {
|
||||
startActivity(new Intent(android.provider.Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
|
||||
Uri.parse("package:" + getPackageName())));
|
||||
} catch (RuntimeException ignored) { }
|
||||
return;
|
||||
}
|
||||
Settings.bubble = true;
|
||||
startService(new Intent(this, BridgeService.class).setAction("BUBBLE").putExtra("on", true));
|
||||
} else {
|
||||
Settings.bubble = false;
|
||||
startService(new Intent(this, BridgeService.class).setAction("BUBBLE").putExtra("on", false));
|
||||
}
|
||||
});
|
||||
bub.addView(sub("A draggable chat-head: tap toggles the SDL3 driver (green on / red off), hold 3s opens this app, "
|
||||
+ "drag to the bottom to remove. Needs the \"Draw over other apps\" permission.", 11f));
|
||||
|
||||
// ---- USB audio ----
|
||||
LinearLayout aud = card(root);
|
||||
cardTitle(aud, "USB audio");
|
||||
audioView = sub(audioInfo(), 12f);
|
||||
aud.addView(audioView);
|
||||
aud.addView(button("Developer options → USB audio routing", v -> openDevSettings()));
|
||||
aud.addView(sub("When the controller is plugged in via USB-C, Android may grab it as an audio device and route sound to it. "
|
||||
+ "This opens Developer options — turn ON \"Disable USB audio routing\" to keep audio on the phone. "
|
||||
+ "(If Developer options aren't enabled, tap Build number 7 times in About phone first.)", 11f));
|
||||
|
||||
root.addView(sub("Orange = held now, green = worked at least once. Leave this app open once, then switch to DroidDeck.", 11f));
|
||||
|
||||
ScrollView scroll = new ScrollView(this);
|
||||
scroll.setBackgroundColor(BG);
|
||||
scroll.addView(root);
|
||||
addContentView(scroll, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
|
||||
|
||||
NativeBridge.listeners.add(this);
|
||||
try {
|
||||
startForegroundService(new Intent(this, BridgeService.class));
|
||||
} catch (RuntimeException ignored) { }
|
||||
NativeBridge.applyDriver();
|
||||
NativeBridge.applyRate();
|
||||
NativeBridge.applyOutput();
|
||||
checkUpdate();
|
||||
ui.post(usbRefresh);
|
||||
}
|
||||
|
||||
private void showPlayer(int p) {
|
||||
uiPlayer = p;
|
||||
for (int i = 0; i < playerTabs.length; i++) {
|
||||
boolean sel = i == p;
|
||||
playerTabs[i].setBackground(rounded(sel ? ACCENT : 0x00000000, dp(8)));
|
||||
playerTabs[i].setTextColor(sel ? 0xFF0E1116 : SUB);
|
||||
playerTabs[i].setTypeface(sel ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
|
||||
}
|
||||
playerBox.removeAllViews();
|
||||
buildPlayerSection(playerBox, p);
|
||||
}
|
||||
|
||||
private void buildPlayerSection(LinearLayout box, final int p) {
|
||||
subhead(box, "Gyro");
|
||||
addSlider(box, "Gyro speed % (100 = 1:1)", 800, Settings.gyroGain[p], v -> Settings.gyroGain[p] = Math.max(1, v));
|
||||
addSpinner(box, "Invert gyro axes", Settings.GYRO_INV_NAMES, Settings.gyroInvert[p], v -> { Settings.gyroInvert[p] = v; Settings.save(); });
|
||||
for (int i = 0; i < 3; i++) {
|
||||
final int out = i;
|
||||
addSpinner(box, "DroidDeck gyro " + "XYZ".charAt(i) + " comes from", Settings.AXIS_NAMES, Settings.gyroMap[p][i], v -> { Settings.gyroMap[p][out] = v; Settings.save(); });
|
||||
}
|
||||
addSpinner(box, "Apply remap/invert to accelerometer too", new String[] { "Yes (recommended)", "No" },
|
||||
Settings.accelFollows[p] ? 0 : 1, v -> { Settings.accelFollows[p] = v == 0; Settings.save(); });
|
||||
addSlider(box, "Gyro deadzone (deg/s)", 50, Settings.gyroDeadzone[p], v -> Settings.gyroDeadzone[p] = v);
|
||||
gyroCalibView = sub(calibLabel(p), 11f);
|
||||
LinearLayout gc = new LinearLayout(this);
|
||||
gc.setOrientation(LinearLayout.HORIZONTAL);
|
||||
gc.addView(button("Calibrate (hold still)", v -> startGyroCalibration()), weight());
|
||||
gap(gc);
|
||||
gc.addView(button("Reset calibration", v -> resetGyroCalibration()), weight());
|
||||
box.addView(gc);
|
||||
box.addView(gyroCalibView);
|
||||
box.addView(sub("Calibration samples the controller shown above (player 1 slot). Deadzone ignores tiny drift.", 11f));
|
||||
|
||||
subhead(box, "Touchpad");
|
||||
addCheck(box, "Invert touchpad X (left/right)", Settings.touchInvX[p], on -> Settings.touchInvX[p] = on);
|
||||
addCheck(box, "Invert touchpad Y (up/down)", Settings.touchInvY[p], on -> Settings.touchInvY[p] = on);
|
||||
addCheck(box, "Swap touchpad X and Y (before invert)", Settings.touchSwap[p], on -> Settings.touchSwap[p] = on);
|
||||
addSpinner(box, "Layout", Settings.TOUCH_NAMES, Settings.touchMode[p], v -> { Settings.touchMode[p] = v; Settings.save(); pad.postInvalidate(); });
|
||||
|
||||
subhead(box, "Button remap");
|
||||
box.addView(sub("Map any controller button to a Deck grip (L4/R4/L5/R5) or a trackpad touch/click. "
|
||||
+ "Useful for extra buttons like a Flydigi's C and Z.", 11f));
|
||||
for (int i = 0; i < Settings.REMAP_COUNT; i++) {
|
||||
final int target = i;
|
||||
addSpinner(box, Settings.REMAP_TARGETS[i] + " pressed by", Settings.SRC_NAMES, Settings.remap[p][i], v -> { Settings.remap[p][target] = v; Settings.save(); });
|
||||
}
|
||||
|
||||
subhead(box, "Light");
|
||||
addSlider(box, "Red", 255, Settings.lightR[p], v -> { Settings.lightR[p] = v; applyLight(p); });
|
||||
addSlider(box, "Green", 255, Settings.lightG[p], v -> { Settings.lightG[p] = v; applyLight(p); });
|
||||
addSlider(box, "Blue", 255, Settings.lightB[p], v -> { Settings.lightB[p] = v; applyLight(p); });
|
||||
addSlider(box, "Brightness %", 100, Settings.brightness[p], v -> { Settings.brightness[p] = v; applyLight(p); });
|
||||
addSpinner(box, "Player LEDs", Settings.PLAYER_NAMES, Settings.playerLed[p], v -> { Settings.playerLed[p] = v; Settings.save(); applyLight(p); });
|
||||
}
|
||||
|
||||
private void applyLight(int p) { NativeBridge.applyOutput(p); }
|
||||
|
||||
// ---------- styled UI helpers ----------
|
||||
|
||||
private GradientDrawable rounded(int color, int radius) {
|
||||
GradientDrawable g = new GradientDrawable();
|
||||
g.setColor(color);
|
||||
g.setCornerRadius(radius);
|
||||
return g;
|
||||
}
|
||||
|
||||
private GradientDrawable pill(int color) {
|
||||
GradientDrawable g = new GradientDrawable();
|
||||
g.setColor(color);
|
||||
g.setCornerRadius(dp(20));
|
||||
return g;
|
||||
}
|
||||
|
||||
private LinearLayout card(LinearLayout parent) {
|
||||
LinearLayout c = new LinearLayout(this);
|
||||
c.setOrientation(LinearLayout.VERTICAL);
|
||||
c.setBackground(rounded(CARD, dp(16)));
|
||||
c.setPadding(dp(16), dp(14), dp(16), dp(14));
|
||||
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
lp.bottomMargin = dp(12);
|
||||
parent.addView(c, lp);
|
||||
return c;
|
||||
}
|
||||
|
||||
private void cardTitle(LinearLayout card, String s) {
|
||||
TextView t = new TextView(this);
|
||||
t.setText(s.toUpperCase(java.util.Locale.ROOT));
|
||||
t.setTextColor(ACCENT);
|
||||
t.setTextSize(12f);
|
||||
t.setTypeface(Typeface.DEFAULT_BOLD);
|
||||
t.setLetterSpacing(0.08f);
|
||||
t.setPadding(0, 0, 0, dp(8));
|
||||
card.addView(t);
|
||||
}
|
||||
|
||||
private void subhead(LinearLayout box, String s) {
|
||||
TextView t = new TextView(this);
|
||||
t.setText(s);
|
||||
t.setTextColor(TEXT);
|
||||
t.setTextSize(14f);
|
||||
t.setTypeface(Typeface.DEFAULT_BOLD);
|
||||
t.setPadding(0, dp(14), 0, dp(4));
|
||||
box.addView(t);
|
||||
}
|
||||
|
||||
private void spacer(LinearLayout parent, int h) {
|
||||
View v = new View(this);
|
||||
parent.addView(v, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(h)));
|
||||
}
|
||||
|
||||
private void gap(LinearLayout row) {
|
||||
View v = new View(this);
|
||||
row.addView(v, new LinearLayout.LayoutParams(dp(8), 1));
|
||||
}
|
||||
|
||||
private TextView text(String s, float size) {
|
||||
TextView t = new TextView(this);
|
||||
t.setTextColor(TEXT);
|
||||
t.setTextSize(size);
|
||||
t.setPadding(0, dp(4), 0, dp(4));
|
||||
t.setText(s);
|
||||
return t;
|
||||
}
|
||||
|
||||
private TextView sub(String s, float size) {
|
||||
TextView t = text(s, size);
|
||||
t.setTextColor(SUB);
|
||||
t.setLineSpacing(dp(2), 1f);
|
||||
return t;
|
||||
}
|
||||
|
||||
private Button button(String s, View.OnClickListener l) {
|
||||
Button b = new Button(this);
|
||||
b.setText(s);
|
||||
b.setAllCaps(false);
|
||||
b.setTextSize(13f);
|
||||
b.setTextColor(TEXT);
|
||||
b.setBackground(rounded(CARD2, dp(10)));
|
||||
b.setStateListAnimator(null);
|
||||
b.setPadding(dp(14), dp(10), dp(14), dp(10));
|
||||
b.setOnClickListener(l);
|
||||
return b;
|
||||
}
|
||||
|
||||
private Button primaryButton(String s, View.OnClickListener l) {
|
||||
Button b = button(s, l);
|
||||
b.setBackground(rounded(ACCENT, dp(10)));
|
||||
b.setTextColor(0xFF0E1116);
|
||||
b.setTypeface(Typeface.DEFAULT_BOLD);
|
||||
return b;
|
||||
}
|
||||
|
||||
private static LinearLayout.LayoutParams weight() {
|
||||
return new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f);
|
||||
}
|
||||
|
||||
private ArrayAdapter<String> styledAdapter(String[] names) {
|
||||
return new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, names) {
|
||||
@Override public View getView(int pos, View cv, ViewGroup parent) {
|
||||
TextView t = (TextView) super.getView(pos, cv, parent);
|
||||
t.setTextColor(TEXT); t.setTextSize(13f);
|
||||
return t;
|
||||
}
|
||||
@Override public View getDropDownView(int pos, View cv, ViewGroup parent) {
|
||||
TextView t = (TextView) super.getDropDownView(pos, cv, parent);
|
||||
t.setTextColor(0xFF10151C); t.setTextSize(14f);
|
||||
t.setPadding(dp(14), dp(12), dp(14), dp(12));
|
||||
return t;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private void addSpinner(LinearLayout root, String label, String[] names, int selected, final IntSink sink) {
|
||||
root.addView(sub(label, 12f));
|
||||
Spinner sp = new Spinner(this);
|
||||
sp.setAdapter(styledAdapter(names));
|
||||
sp.setSelection(selected);
|
||||
sp.setBackground(rounded(CARD2, dp(8)));
|
||||
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
lp.bottomMargin = dp(6);
|
||||
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
|
||||
@Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { sink.set(position); }
|
||||
@Override public void onNothingSelected(AdapterView<?> parent) { }
|
||||
});
|
||||
root.addView(sp, lp);
|
||||
}
|
||||
|
||||
private void addSlider(LinearLayout root, final String label, int max, int value, final IntSink sink) {
|
||||
final TextView t = sub(label + ": " + value, 12f);
|
||||
SeekBar sb = new SeekBar(this);
|
||||
sb.setMax(max);
|
||||
sb.setProgress(value);
|
||||
sb.setProgressTintList(ColorStateList.valueOf(ACCENT));
|
||||
sb.setThumbTintList(ColorStateList.valueOf(ACCENT));
|
||||
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
|
||||
@Override public void onProgressChanged(SeekBar s, int v, boolean fromUser) {
|
||||
t.setText(label + ": " + v);
|
||||
if (fromUser) sink.set(v);
|
||||
}
|
||||
@Override public void onStartTrackingTouch(SeekBar s) { }
|
||||
@Override public void onStopTrackingTouch(SeekBar s) { Settings.save(); }
|
||||
});
|
||||
root.addView(t);
|
||||
root.addView(sb);
|
||||
}
|
||||
|
||||
private interface BoolSink { void set(boolean on); }
|
||||
|
||||
private void addCheck(LinearLayout root, String label, boolean value, final BoolSink sink) {
|
||||
CheckBox c = new CheckBox(this);
|
||||
c.setText(label);
|
||||
c.setTextColor(TEXT);
|
||||
c.setTextSize(13f);
|
||||
c.setButtonTintList(ColorStateList.valueOf(ACCENT));
|
||||
c.setPadding(dp(6), dp(6), 0, dp(6));
|
||||
c.setChecked(value);
|
||||
c.setOnCheckedChangeListener((v, on) -> { sink.set(on); Settings.save(); });
|
||||
root.addView(c);
|
||||
}
|
||||
|
||||
// ---------- USB diagnostics ----------
|
||||
|
||||
private final Runnable usbRefresh = new Runnable() {
|
||||
@Override public void run() {
|
||||
int n = BridgeService.clientCount;
|
||||
usbView.setText(usbInfo() + "\nDroidDeck link: " + (n > 0 ? (n + " app(s) bound — sending frames") : "NOT bound (open a DroidDeck game session)"));
|
||||
ui.postDelayed(this, 2000);
|
||||
}
|
||||
};
|
||||
|
||||
/** Android's view of the controller on USB: is it there, and may this app talk to it? */
|
||||
private String usbInfo() {
|
||||
try {
|
||||
UsbManager um = (UsbManager) getSystemService(USB_SERVICE);
|
||||
StringBuilder sb = new StringBuilder("USB: ");
|
||||
boolean any = false;
|
||||
for (UsbDevice d : um.getDeviceList().values()) {
|
||||
if (!looksLikeController(d)) continue;
|
||||
any = true;
|
||||
String name = d.getProductName() != null ? d.getProductName() : "controller";
|
||||
sb.append(String.format(java.util.Locale.ROOT, "%s %04x:%04x access=%s ", name,
|
||||
d.getVendorId(), d.getProductId(), um.hasPermission(d) ? "yes" : "NO (unplug and replug, tap OK)"));
|
||||
}
|
||||
if (!any) sb.append("no controller on USB (use a USB-C data cable)");
|
||||
return sb.toString();
|
||||
} catch (RuntimeException e) {
|
||||
return "USB: unavailable";
|
||||
}
|
||||
}
|
||||
|
||||
/** Lists any USB / headset audio outputs Android currently sees (e.g. the controller's audio device). */
|
||||
private int rateIndex() {
|
||||
for (int i = 0; i < Settings.RATE_MS.length; i++) if (Settings.RATE_MS[i] == Settings.pollMs) return i;
|
||||
return 1;
|
||||
}
|
||||
|
||||
private String audioInfo() {
|
||||
try {
|
||||
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
|
||||
StringBuilder sb = new StringBuilder("Audio out: ");
|
||||
boolean any = false;
|
||||
for (AudioDeviceInfo d : am.getDevices(AudioManager.GET_DEVICES_OUTPUTS)) {
|
||||
int t = d.getType();
|
||||
if (t == AudioDeviceInfo.TYPE_USB_DEVICE || t == AudioDeviceInfo.TYPE_USB_HEADSET || t == AudioDeviceInfo.TYPE_USB_ACCESSORY) {
|
||||
any = true;
|
||||
CharSequence nm = d.getProductName();
|
||||
sb.append(nm != null ? nm : (t == AudioDeviceInfo.TYPE_USB_HEADSET ? "USB headset" : "USB audio")).append(" ");
|
||||
}
|
||||
}
|
||||
if (!any) sb.append("no USB audio device (plug the controller in with USB-C, or no audio interface)");
|
||||
return sb.toString();
|
||||
} catch (RuntimeException e) {
|
||||
return "Audio out: unavailable";
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens Developer options, where "Disable USB audio routing" keeps audio on the phone. */
|
||||
private void openDevSettings() {
|
||||
// There is no public intent to a single developer toggle, so open the Developer options screen.
|
||||
try {
|
||||
startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
|
||||
return;
|
||||
} catch (RuntimeException ignored) { }
|
||||
// Developer options not enabled or unavailable: fall back to the main Settings app.
|
||||
try {
|
||||
startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
|
||||
} catch (RuntimeException ignored) { }
|
||||
}
|
||||
|
||||
// ---------- tests ----------
|
||||
|
||||
private void rumbleTest() {
|
||||
NativeBridge.setRumble(uiPlayer, 220, 220);
|
||||
ui.postDelayed(() -> NativeBridge.setRumble(uiPlayer, 0, 0), 700);
|
||||
}
|
||||
|
||||
// ---------- updates ----------
|
||||
|
||||
private void checkUpdate() {
|
||||
updateUrl = null;
|
||||
updateButton.setText("Checking for updates...");
|
||||
UpdateChecker.check(this, (msg, url) -> {
|
||||
updateUrl = url;
|
||||
updateButton.setText(msg);
|
||||
});
|
||||
}
|
||||
|
||||
private void openUrl(String url) {
|
||||
try {
|
||||
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
|
||||
} catch (RuntimeException e) {
|
||||
updateButton.setText("Could not open the download link.");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- SDL USB handling ----------
|
||||
|
||||
@Override protected void onDestroy() {
|
||||
running = false;
|
||||
ui.removeCallbacks(usbRefresh);
|
||||
NativeBridge.listeners.remove(this);
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
// SDL releases the USB controller when the activity pauses or loses focus. Undo that so input
|
||||
// keeps flowing while DroidDeck is in front.
|
||||
/** Asks Android for USB access to every game-controller-like device, using SDL's own permission
|
||||
* action so SDL's receiver opens the device straight away, then restarts SDL's enumeration. */
|
||||
private void forceUsbDriver() {
|
||||
UsbManager um = (UsbManager) getSystemService(USB_SERVICE);
|
||||
int asked = 0, have = 0, seen = 0;
|
||||
if (um != null) {
|
||||
for (UsbDevice d : um.getDeviceList().values()) {
|
||||
if (!looksLikeController(d)) continue;
|
||||
seen++;
|
||||
if (um.hasPermission(d)) { have++; continue; }
|
||||
Intent i = new Intent("org.libsdl.app.USB_PERMISSION").setPackage(getPackageName());
|
||||
int flags = Build.VERSION.SDK_INT >= 31 ? 0x02000000 : 0; // FLAG_MUTABLE
|
||||
try {
|
||||
um.requestPermission(d, PendingIntent.getBroadcast(this, 0, i, flags));
|
||||
asked++;
|
||||
} catch (RuntimeException ignored) { }
|
||||
}
|
||||
}
|
||||
usbView.setText(seen == 0
|
||||
? "No USB controller found. Use a USB-C cable (Bluetooth is not enough) and try again."
|
||||
: "USB controllers: " + seen + ", already allowed: " + have + ", asked now: " + asked);
|
||||
keepControllerClaimed();
|
||||
ui.postDelayed(NativeBridge::rescan, asked > 0 ? 4000 : 300);
|
||||
}
|
||||
|
||||
/** Any USB device with a HID or vendor-specific interface (SDL3 decides whether it really is a controller). */
|
||||
private static boolean looksLikeController(UsbDevice d) {
|
||||
for (int n = 0; n < d.getInterfaceCount(); n++) {
|
||||
UsbInterface f = d.getInterface(n);
|
||||
int c = f.getInterfaceClass();
|
||||
if (c == 255 || (c == 3 && f.getInterfaceProtocol() == 0)) return true; // vendor-specific (Xbox) or generic HID
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override protected void onResume() {
|
||||
super.onResume();
|
||||
if (android.provider.Settings.canDrawOverlays(this)) {
|
||||
if (pendingBubble) {
|
||||
pendingBubble = false;
|
||||
Settings.bubble = true;
|
||||
Settings.save();
|
||||
}
|
||||
if (Settings.bubble) {
|
||||
startService(new Intent(this, BridgeService.class).setAction("BUBBLE").putExtra("on", true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override protected void onPause() {
|
||||
super.onPause();
|
||||
if (isFinishing()) running = false;
|
||||
keepControllerClaimed();
|
||||
}
|
||||
|
||||
@Override public void onBackPressed() {
|
||||
// Fallback only: SDL3 runs in a screen behind this one, and closing them would stop it -- step back instead.
|
||||
if (SdlHostActivity.running) moveTaskToBack(true);
|
||||
else super.onBackPressed();
|
||||
}
|
||||
|
||||
@Override public void onWindowFocusChanged(boolean hasFocus) {
|
||||
super.onWindowFocusChanged(hasFocus);
|
||||
keepControllerClaimed();
|
||||
}
|
||||
|
||||
private void keepControllerClaimed() {
|
||||
// When the driver is off, let go of the controller (freeze = release the USB interface) so Android can use it.
|
||||
SdlEngine.setHidFrozen(!Settings.driverEnabled);
|
||||
}
|
||||
|
||||
/** Release or re-claim the USB interface (the driver was switched off / on). */
|
||||
static void setHidFrozen(boolean frozen) {
|
||||
SdlEngine.setHidFrozen(frozen);
|
||||
}
|
||||
|
||||
// Controllers that reach the phone through Android's input (Bluetooth) deliver their buttons and sticks to the
|
||||
// focused window: while this screen is in front, hand them to SDL like SDL's own activity did.
|
||||
private static boolean fromGamepad(int source) {
|
||||
return (source & android.view.InputDevice.SOURCE_GAMEPAD) == android.view.InputDevice.SOURCE_GAMEPAD
|
||||
|| (source & android.view.InputDevice.SOURCE_JOYSTICK) == android.view.InputDevice.SOURCE_JOYSTICK
|
||||
|| (source & android.view.InputDevice.SOURCE_DPAD) == android.view.InputDevice.SOURCE_DPAD;
|
||||
}
|
||||
|
||||
@Override public boolean dispatchKeyEvent(android.view.KeyEvent e) {
|
||||
if (SdlEngine.isRunning() && fromGamepad(e.getSource())) {
|
||||
try {
|
||||
if (SDLControllerManager.isDeviceSDLJoystick(e.getDeviceId())) {
|
||||
if (e.getAction() == android.view.KeyEvent.ACTION_DOWN
|
||||
&& SDLControllerManager.onNativePadDown(e.getDeviceId(), e.getKeyCode(), e.getScanCode())) return true;
|
||||
if (e.getAction() == android.view.KeyEvent.ACTION_UP
|
||||
&& SDLControllerManager.onNativePadUp(e.getDeviceId(), e.getKeyCode(), e.getScanCode())) return true;
|
||||
}
|
||||
} catch (UnsatisfiedLinkError | RuntimeException ignored) { }
|
||||
}
|
||||
return super.dispatchKeyEvent(e);
|
||||
}
|
||||
|
||||
@Override public boolean dispatchGenericMotionEvent(android.view.MotionEvent e) {
|
||||
if (SdlEngine.isRunning() && (e.getSource() & android.view.InputDevice.SOURCE_JOYSTICK) == android.view.InputDevice.SOURCE_JOYSTICK) {
|
||||
try {
|
||||
if (SDLControllerManager.handleJoystickMotionEvent(e)) return true;
|
||||
} catch (UnsatisfiedLinkError | RuntimeException ignored) { }
|
||||
}
|
||||
return super.dispatchGenericMotionEvent(e);
|
||||
}
|
||||
|
||||
// ---------- NativeBridge.Listener ----------
|
||||
|
||||
private String calibLabel(int p) {
|
||||
float[] b = Settings.gyroBias[p];
|
||||
if (b[0] == 0f && b[1] == 0f && b[2] == 0f) return "Calibration: none";
|
||||
return String.format(java.util.Locale.ROOT, "Calibration bias (deg/s): x=%.2f y=%.2f z=%.2f", b[0], b[1], b[2]);
|
||||
}
|
||||
|
||||
private void startGyroCalibration() {
|
||||
calibPlayer = uiPlayer;
|
||||
calibSum[0] = calibSum[1] = calibSum[2] = 0f;
|
||||
calibCount = 0;
|
||||
if (gyroCalibView != null) gyroCalibView.setText("Hold the controller still...");
|
||||
}
|
||||
|
||||
private void resetGyroCalibration() {
|
||||
calibCount = -1;
|
||||
float[] b = Settings.gyroBias[uiPlayer];
|
||||
b[0] = b[1] = b[2] = 0f;
|
||||
Settings.save();
|
||||
if (gyroCalibView != null) gyroCalibView.setText(calibLabel(uiPlayer));
|
||||
}
|
||||
|
||||
@Override public void onFrame(float[] f, int slot) {
|
||||
if (slot != 0) return; // the test screen shows player 1
|
||||
if (calibCount >= 0 && f.length >= 13) {
|
||||
calibSum[0] += f[7]; calibSum[1] += f[8]; calibSum[2] += f[9];
|
||||
if (++calibCount >= CALIB_SAMPLES) {
|
||||
float[] b = Settings.gyroBias[calibPlayer];
|
||||
b[0] = calibSum[0] / CALIB_SAMPLES * RAD_TO_DEG;
|
||||
b[1] = calibSum[1] / CALIB_SAMPLES * RAD_TO_DEG;
|
||||
b[2] = calibSum[2] / CALIB_SAMPLES * RAD_TO_DEG;
|
||||
Settings.save();
|
||||
calibCount = -1;
|
||||
ui.post(() -> { if (gyroCalibView != null && uiPlayer == calibPlayer) gyroCalibView.setText(calibLabel(calibPlayer)); });
|
||||
}
|
||||
}
|
||||
pad.update(f);
|
||||
long now = System.nanoTime();
|
||||
if (now - lastSummary > 300_000_000L) {
|
||||
lastSummary = now;
|
||||
ui.post(() -> summaryView.setText(pad.summary()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onPadCaps(int slot, int present, int axes, int touchpads, String kind) {
|
||||
if (slot != 0) return;
|
||||
pad.setCaps(present, axes, touchpads, kind);
|
||||
}
|
||||
|
||||
@Override public void onStatus(final String s) {
|
||||
ui.post(() -> {
|
||||
statusView.setText(s);
|
||||
boolean off = s.contains("driver OFF");
|
||||
boolean waiting = s.startsWith("Controller disconnected") || s.startsWith("Waiting") || s.startsWith("Starting");
|
||||
if (off) {
|
||||
statusPill.setText("Driver off");
|
||||
statusPill.setBackground(pill(BADC));
|
||||
} else if (waiting) {
|
||||
statusPill.setText("Waiting");
|
||||
statusPill.setBackground(pill(WARNC));
|
||||
} else {
|
||||
statusPill.setText("Connected");
|
||||
statusPill.setBackground(pill(OKC));
|
||||
}
|
||||
if (off || waiting) pad.setDisconnected();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,975 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ServiceInfo;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.PixelFormat;
|
||||
import android.graphics.drawable.GradientDrawable;
|
||||
import android.util.TypedValue;
|
||||
import android.view.Gravity;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.TextView;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.IBinder;
|
||||
import android.os.Looper;
|
||||
import android.os.Message;
|
||||
import android.os.Messenger;
|
||||
import android.os.RemoteException;
|
||||
import android.os.SystemClock;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/**
|
||||
* Streams controller frames (from the SDL3 loop) to bound clients such as DroidDeck, and passes their
|
||||
* rumble / lightbar requests back. Same wire protocol as the first bridge, plus decoupled touchpad data.
|
||||
*/
|
||||
public class BridgeService extends Service implements NativeBridge.Listener {
|
||||
static final int MSG_REGISTER = 1;
|
||||
static final int MSG_UNREGISTER = 2;
|
||||
static final int MSG_OUTPUT = 3;
|
||||
static final int MSG_FRAME = 10;
|
||||
static final int MSG_STATUS = 11;
|
||||
static final int MSG_PAD_GONE = 12;
|
||||
// Steam Controller (2026) raw passthrough. Client -> bridge:
|
||||
static final int MSG_TRITON_OUTPUT = 4; // "data": report (id first), "feature": feature write?
|
||||
static final int MSG_TRITON_GET = 5; // "request": long, "id": feature report id
|
||||
static final int MSG_TRITON_RUMBLE = 6; // "l", "r": 0..65535
|
||||
// Bridge -> client:
|
||||
static final int MSG_TRITON_STATE = 13; // "id": report id, "data": payload
|
||||
static final int MSG_TRITON_CONN = 14; // "on": boolean, "what": description
|
||||
static final int MSG_TRITON_FEATURE = 15; // "request": long, "data": reply (absent = no answer)
|
||||
// Steam Native Hook-up. Client -> bridge:
|
||||
static final int MSG_HOOKUP_OUT = 7; // "slot", "kind" (0 output report, 1 feature write), "data"
|
||||
static final int MSG_HOOKUP_GET = 8; // "slot", "request", "id", "input", "length"
|
||||
// Bridge -> client:
|
||||
static final int MSG_HOOKUP_ADD = 20; // HookupIdentity bundle
|
||||
static final int MSG_HOOKUP_INPUT = 21; // "slot", "data"
|
||||
static final int MSG_HOOKUP_REMOVE = 22; // "slot"
|
||||
static final int MSG_HOOKUP_REPLY = 23; // "slot", "request", "data" (absent = no answer)
|
||||
static final int MSG_BRIDGE_LOG = 30; // "text": one or more log lines (newline separated)
|
||||
static final int MSG_HOOKUP_SYNC = 9; // client watchdog: resend what is handed over (re-registers if needed)
|
||||
static final int MSG_HOOKUP_STATE = 24; // "slots": int[] of live hook-up slots; "fast_ino": mapped shared file
|
||||
static final int MSG_HOOKUP_SHM = 25; // <- DroidDeck: "fd": its shared hook-up file (fast path)
|
||||
// DroidDeck's SDL3Bridge settings tab (no REGISTER needed: it gets no frames, only replies)
|
||||
static final int MSG_SETTINGS_GET = 40; // <- replyTo: send MSG_SETTINGS
|
||||
static final int MSG_SETTINGS_SET = 41; // <- "key" [+ "p" player, "i" index] + "int" / "bool"; replyTo: send MSG_SETTINGS
|
||||
static final int MSG_SETTINGS = 42; // -> the whole settings state + controller status (see settingsSnapshot)
|
||||
|
||||
private static final float RAD_TO_DEG = 57.29578f;
|
||||
private static final float G = 9.80665f;
|
||||
private static final float PAD_W = 1920f, PAD_H = 1080f;
|
||||
|
||||
private final CopyOnWriteArrayList<Messenger> clients = new CopyOnWriteArrayList<>();
|
||||
static volatile int clientCount; // how many clients (DroidDeck) are bound + registered
|
||||
|
||||
private final Handler handler = new Handler(Looper.getMainLooper()) {
|
||||
@Override public void handleMessage(Message m) {
|
||||
switch (m.what) {
|
||||
case MSG_REGISTER:
|
||||
if (m.replyTo != null) {
|
||||
if (!clients.contains(m.replyTo)) clients.add(m.replyTo); // re-register = resend state, no duplicate
|
||||
clientCount = clients.size(); sendStatus(m.replyTo, NativeBridge.lastStatus);
|
||||
if (NativeBridge.tritonConnected) sendTritonConn(m.replyTo, true, NativeBridge.tritonWhat);
|
||||
String backlog;
|
||||
synchronized (NativeBridge.bridgeLog) { backlog = String.join("\n", NativeBridge.bridgeLog); }
|
||||
if (!backlog.isEmpty()) {
|
||||
Bundle lb = new Bundle();
|
||||
lb.putString("text", "(earlier) " + backlog.replace("\n", "\n(earlier) "));
|
||||
sendOne(m.replyTo, MSG_BRIDGE_LOG, lb);
|
||||
}
|
||||
for (Bundle id : NativeBridge.hookupIdentity) if (id != null) sendOne(m.replyTo, MSG_HOOKUP_ADD, id);
|
||||
}
|
||||
break;
|
||||
case MSG_UNREGISTER:
|
||||
if (m.replyTo != null) { clients.remove(m.replyTo); clientCount = clients.size(); }
|
||||
if (clients.isEmpty()) NativeBridge.setSteamAway(false); // DroidDeck's session ended
|
||||
break;
|
||||
case MSG_OUTPUT:
|
||||
mergeOutput(m.getData());
|
||||
break;
|
||||
case MSG_TRITON_OUTPUT: {
|
||||
byte[] data = m.getData().getByteArray("data");
|
||||
if (data != null) NativeBridge.tritonOutput(data, m.getData().getBoolean("feature"));
|
||||
break;
|
||||
}
|
||||
case MSG_TRITON_GET:
|
||||
NativeBridge.tritonGetFeature(m.getData().getLong("request"), m.getData().getInt("id", 1));
|
||||
break;
|
||||
case MSG_HOOKUP_OUT: {
|
||||
byte[] data = m.getData().getByteArray("data");
|
||||
if (data != null) NativeBridge.hookupOutput(m.getData().getInt("slot"), m.getData().getInt("kind"), data);
|
||||
break;
|
||||
}
|
||||
case MSG_HOOKUP_SYNC:
|
||||
// DroidDeck's desktop: is the Steam client running there? (Absent = yes: the Steam session.)
|
||||
NativeBridge.setSteamAway(m.getData() != null && m.getData().getBoolean("steamAway", false));
|
||||
handler.removeCallbacks(steamAwayLapse);
|
||||
if (NativeBridge.hookupWaitsForSteam()) handler.postDelayed(steamAwayLapse, 10100);
|
||||
if (m.replyTo != null) {
|
||||
// A client the bridge forgot (the bridge was restarted) is registered again.
|
||||
if (!clients.contains(m.replyTo)) {
|
||||
clients.add(m.replyTo); clientCount = clients.size();
|
||||
sendStatus(m.replyTo, NativeBridge.lastStatus);
|
||||
}
|
||||
if (NativeBridge.tritonConnected) sendTritonConn(m.replyTo, true, NativeBridge.tritonWhat);
|
||||
int[] live = new int[NativeBridge.MAX_PADS];
|
||||
int n = 0;
|
||||
for (int i = 0; i < NativeBridge.MAX_PADS; i++) {
|
||||
Bundle id = NativeBridge.hookupIdentity[i];
|
||||
if (id == null) continue;
|
||||
sendOne(m.replyTo, MSG_HOOKUP_ADD, id);
|
||||
live[n++] = i;
|
||||
}
|
||||
NativeBridge.retryUndescribed();
|
||||
Bundle st = new Bundle();
|
||||
st.putIntArray("slots", java.util.Arrays.copyOf(live, n));
|
||||
st.putLong("fast_ino", NativeBridge.hookupShmInode());
|
||||
sendOne(m.replyTo, MSG_HOOKUP_STATE, st);
|
||||
}
|
||||
ensureBridgeLoop();
|
||||
break;
|
||||
case MSG_HOOKUP_SHM: {
|
||||
Bundle d = m.getData();
|
||||
if (d != null) d.setClassLoader(android.os.ParcelFileDescriptor.class.getClassLoader());
|
||||
@SuppressWarnings("deprecation")
|
||||
android.os.ParcelFileDescriptor pfd = d == null ? null : d.getParcelable("fd");
|
||||
NativeBridge.hookupMapShm(pfd);
|
||||
break;
|
||||
}
|
||||
case MSG_SETTINGS_SET:
|
||||
applyRemote(m.getData());
|
||||
// fall through: answer with the new state
|
||||
case MSG_SETTINGS_GET:
|
||||
if (m.replyTo != null) sendOne(m.replyTo, MSG_SETTINGS, settingsSnapshot());
|
||||
if (m.what == MSG_SETTINGS_GET) ensureBridgeLoop(); // the tab shows live controllers
|
||||
break;
|
||||
case MSG_HOOKUP_GET:
|
||||
NativeBridge.hookupGet(m.getData().getInt("slot"), m.getData().getLong("request"), m.getData().getInt("id"),
|
||||
m.getData().getBoolean("input"), m.getData().getInt("length", 64));
|
||||
break;
|
||||
case MSG_TRITON_RUMBLE:
|
||||
NativeBridge.tritonRumble(m.getData().getInt("l"), m.getData().getInt("r"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
private final Messenger messenger = new Messenger(handler);
|
||||
/** DroidDeck stopped saying that Steam is away (it went away itself): hook-up goes on again. */
|
||||
private final Runnable steamAwayLapse = NativeBridge::recheckHookup;
|
||||
|
||||
// ---- floating bubble ----
|
||||
private final Handler main = new Handler(Looper.getMainLooper());
|
||||
private WindowManager wm;
|
||||
private TextView bubble;
|
||||
private WindowManager.LayoutParams bubbleLp;
|
||||
private int bubbleSize;
|
||||
private View removeZone;
|
||||
private boolean longPressFired;
|
||||
private Runnable bubbleLongPress;
|
||||
private volatile boolean connectedState;
|
||||
|
||||
static volatile BridgeService instance;
|
||||
|
||||
@Override public void onCreate() {
|
||||
NativeBridge.appContext = getApplicationContext();
|
||||
NativeBridge.clients = clients::size;
|
||||
instance = this;
|
||||
super.onCreate();
|
||||
Settings.init(this);
|
||||
NativeBridge.listeners.add(this);
|
||||
// SDL3 runs here, in the background: nothing has to open when DroidDeck (or a plugged-in controller)
|
||||
// starts the bridge. The notification is the bridge's icon in the status bar.
|
||||
SdlEngine.start(this);
|
||||
// The status bar icon. Started by DroidDeck's connection it is a plain ongoing notification (that
|
||||
// connection keeps the bridge alive); started from the bridge screen or a plugged-in controller,
|
||||
// onStartCommand turns it into the foreground service's notification.
|
||||
postNotification(false);
|
||||
}
|
||||
|
||||
// ---------- status bar notification ----------
|
||||
private static final int NOTE_ID = 1;
|
||||
private String noteText = "";
|
||||
private long noteMs;
|
||||
|
||||
private Notification buildNotification() {
|
||||
NotificationManager nm = getSystemService(NotificationManager.class);
|
||||
nm.createNotificationChannel(new NotificationChannel("bridge", "Controller bridge", NotificationManager.IMPORTANCE_LOW));
|
||||
android.app.PendingIntent open = android.app.PendingIntent.getActivity(this, 0,
|
||||
new Intent(this, BridgeActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
android.app.PendingIntent.FLAG_IMMUTABLE | android.app.PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
String text = SdlEngine.error != null ? SdlEngine.error : NativeBridge.lastStatus;
|
||||
return new Notification.Builder(this, "bridge")
|
||||
.setContentTitle(!Settings.isHookup() ? "SDL3Bridge"
|
||||
: NativeBridge.hookupWaitsForSteam() ? "SDL3Bridge · Hook-up waits for Steam (DroidDeck desktop)"
|
||||
: "SDL3Bridge · Steam Native Hook-up")
|
||||
.setContentText(text)
|
||||
.setStyle(new Notification.BigTextStyle().bigText(text))
|
||||
.setSmallIcon(R.drawable.ic_stat_bridge)
|
||||
.setColor(0xFF4FC3F7)
|
||||
.setContentIntent(open)
|
||||
.setOngoing(true)
|
||||
.setShowWhen(false)
|
||||
.setOnlyAlertOnce(true)
|
||||
.build();
|
||||
}
|
||||
|
||||
/** foreground: as the foreground service's notification; else a plain ongoing notification. */
|
||||
private boolean postNotification(boolean foreground) {
|
||||
try {
|
||||
Notification n = buildNotification();
|
||||
if (foreground) {
|
||||
if (Build.VERSION.SDK_INT >= 34) startForeground(NOTE_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE);
|
||||
else startForeground(NOTE_ID, n);
|
||||
} else {
|
||||
getSystemService(NotificationManager.class).notify(NOTE_ID, n);
|
||||
}
|
||||
return true;
|
||||
} catch (RuntimeException e) {
|
||||
android.util.Log.w("SDL3Bridge", "notification: " + e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Status changed: refresh the notification text (at most every 2 s). */
|
||||
private void refreshNotification(String status) {
|
||||
if (status == null || status.equals(noteText)) return;
|
||||
long now = SystemClock.uptimeMillis();
|
||||
if (now - noteMs < 2000) {
|
||||
main.removeCallbacks(noteRefresh);
|
||||
main.postDelayed(noteRefresh, 2000 - (now - noteMs));
|
||||
return;
|
||||
}
|
||||
noteText = status;
|
||||
noteMs = now;
|
||||
try { getSystemService(NotificationManager.class).notify(NOTE_ID, buildNotification()); } catch (RuntimeException ignored) { }
|
||||
}
|
||||
private final Runnable noteRefresh = () -> refreshNotification(NativeBridge.lastStatus);
|
||||
|
||||
@Override public IBinder onBind(Intent i) { return messenger.getBinder(); }
|
||||
|
||||
@Override public int onStartCommand(Intent i, int flags, int startId) {
|
||||
SdlEngine.start(this);
|
||||
if (i != null && "BUBBLE".equals(i.getAction())) {
|
||||
if (i.getBooleanExtra("on", false)) showBubble(); else hideBubble();
|
||||
} else if (Settings.bubble) {
|
||||
showBubble();
|
||||
}
|
||||
if (!postNotification(true)) postNotification(false);
|
||||
return START_NOT_STICKY;
|
||||
}
|
||||
|
||||
@Override public void onDestroy() {
|
||||
if (instance == this) instance = null;
|
||||
NativeBridge.listeners.remove(this);
|
||||
hideBubble();
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
// ---------- floating bubble (chat-head) ----------
|
||||
// tap -> toggle the SDL3 forced driver (green = on, red = off)
|
||||
// double tap -> toggle Steam Native Hook-up (blue = on: Steam gets the real controllers)
|
||||
// hold 3s -> open the bridge app
|
||||
// drag to the bottom remove zone -> dismiss the bubble
|
||||
|
||||
@SuppressWarnings("ClickableViewAccessibility")
|
||||
private void showBubble() {
|
||||
if (bubble != null) return;
|
||||
if (!android.provider.Settings.canDrawOverlays(this)) return; // no permission yet
|
||||
wm = (WindowManager) getSystemService(WINDOW_SERVICE);
|
||||
|
||||
bubbleSize = dp(52);
|
||||
TextView b = new TextView(this);
|
||||
b.setText(Settings.isHookup() ? "HOOK" : "SDL3");
|
||||
b.setTextColor(Color.WHITE);
|
||||
b.setGravity(Gravity.CENTER);
|
||||
b.setTextSize(12f);
|
||||
b.setWidth(bubbleSize);
|
||||
b.setHeight(bubbleSize);
|
||||
b.setBackground(bubbleBg(Settings.driverEnabled));
|
||||
b.setElevation(dp(4));
|
||||
|
||||
int type = Build.VERSION.SDK_INT >= 26
|
||||
? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
|
||||
: WindowManager.LayoutParams.TYPE_PHONE;
|
||||
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
|
||||
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, type,
|
||||
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
|
||||
PixelFormat.TRANSLUCENT);
|
||||
lp.gravity = Gravity.TOP | Gravity.START;
|
||||
lp.x = Settings.bubbleX;
|
||||
lp.y = Settings.bubbleY;
|
||||
|
||||
final int slop = dp(10);
|
||||
b.setOnTouchListener(new View.OnTouchListener() {
|
||||
float downX, downY; int startX, startY; boolean moved;
|
||||
@Override public boolean onTouch(View v, MotionEvent e) {
|
||||
switch (e.getAction()) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
downX = e.getRawX(); downY = e.getRawY();
|
||||
startX = bubbleLp.x; startY = bubbleLp.y; moved = false; longPressFired = false;
|
||||
bubbleLongPress = () -> { longPressFired = true; openBridgeApp(); };
|
||||
main.postDelayed(bubbleLongPress, 3000);
|
||||
return true;
|
||||
case MotionEvent.ACTION_MOVE: {
|
||||
int nx = startX + (int) (e.getRawX() - downX);
|
||||
int ny = startY + (int) (e.getRawY() - downY);
|
||||
if (!moved && Math.abs(nx - startX) + Math.abs(ny - startY) > slop) {
|
||||
moved = true;
|
||||
if (bubbleLongPress != null) main.removeCallbacks(bubbleLongPress);
|
||||
showRemoveZone();
|
||||
}
|
||||
bubbleLp.x = nx; bubbleLp.y = ny;
|
||||
try { wm.updateViewLayout(bubble, bubbleLp); } catch (RuntimeException ignored) { }
|
||||
if (moved) highlightRemoveZone(overRemoveZone());
|
||||
return true;
|
||||
}
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
case MotionEvent.ACTION_UP:
|
||||
if (bubbleLongPress != null) main.removeCallbacks(bubbleLongPress);
|
||||
boolean removed = false;
|
||||
if (moved && overRemoveZone()) { removeBubbleByUser(); removed = true; }
|
||||
hideRemoveZone();
|
||||
if (!removed) {
|
||||
Settings.bubbleX = bubbleLp.x; Settings.bubbleY = bubbleLp.y; Settings.save();
|
||||
if (!moved && !longPressFired) onBubbleTap();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
wm.addView(b, lp);
|
||||
bubble = b;
|
||||
bubbleLp = lp;
|
||||
} catch (RuntimeException e) {
|
||||
bubble = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void openBridgeApp() {
|
||||
try {
|
||||
startActivity(new Intent(BridgeService.this, BridgeActivity.class)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
|
||||
} catch (RuntimeException ignored) { }
|
||||
}
|
||||
|
||||
// A single tap waits this long for a second tap before it acts, so a double tap doesn't also flip the driver.
|
||||
private static final long DOUBLE_TAP_MS = 300;
|
||||
private boolean tapPending;
|
||||
|
||||
private void onBubbleTap() {
|
||||
if (tapPending) {
|
||||
tapPending = false; // the pending single tap sees this and does nothing
|
||||
toggleHookup();
|
||||
} else {
|
||||
tapPending = true;
|
||||
main.postDelayed(() -> { if (tapPending) { tapPending = false; toggleDriver(); } }, DOUBLE_TAP_MS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Double-tap action: Steam Native Hook-up on/off. Hook-up needs the SDL3 driver, so switching it on also
|
||||
* switches the driver on; switching it off puts back what was there before -- including the driver being
|
||||
* off (red bubble), so the controller goes back to Android / DroidDeck's own input instead of SDL3.
|
||||
*/
|
||||
private void toggleHookup() {
|
||||
boolean on = !Settings.isHookup();
|
||||
boolean freeze = false;
|
||||
if (on) {
|
||||
Settings.lastPresentAs = Settings.presentAs;
|
||||
Settings.driverBeforeHookup = Settings.driverEnabled;
|
||||
Settings.presentAs = Settings.PRESENT_HOOKUP;
|
||||
if (!Settings.driverEnabled) {
|
||||
Settings.driverEnabled = true;
|
||||
try { SdlEngine.setHidFrozen(false); } catch (Throwable ignored) { }
|
||||
}
|
||||
} else {
|
||||
Settings.presentAs = Settings.lastPresentAs;
|
||||
if (!Settings.driverBeforeHookup && Settings.driverEnabled) {
|
||||
Settings.driverEnabled = false;
|
||||
freeze = true;
|
||||
}
|
||||
}
|
||||
Settings.save();
|
||||
NativeBridge.applyDriver(); // also applies hook-up (native code releases the hooked-up controllers)
|
||||
if (freeze) {
|
||||
try { SdlEngine.setHidFrozen(true); } catch (Throwable ignored) { }
|
||||
}
|
||||
updateBubble();
|
||||
try {
|
||||
android.widget.Toast.makeText(this, on
|
||||
? "Steam Native Hook-up ON: Steam gets the real USB controllers"
|
||||
: !Settings.driverEnabled ? "Steam Native Hook-up OFF: SDL3 driver off again"
|
||||
: "Steam Native Hook-up OFF: back to " + Settings.PRESENT_NAMES[Settings.presentAs],
|
||||
android.widget.Toast.LENGTH_SHORT).show();
|
||||
} catch (RuntimeException ignored) { }
|
||||
}
|
||||
|
||||
/** Recolor the bubble after a settings change made elsewhere (the app screen). */
|
||||
static void refreshBubble() {
|
||||
BridgeService s = instance;
|
||||
if (s != null) s.updateBubble();
|
||||
}
|
||||
|
||||
/** Tap action: flip the SDL3 forced driver and recolor the bubble. */
|
||||
private void toggleDriver() {
|
||||
Settings.driverEnabled = !Settings.driverEnabled;
|
||||
Settings.save();
|
||||
NativeBridge.applyDriver();
|
||||
try { SdlEngine.setHidFrozen(!Settings.driverEnabled); } catch (Throwable ignored) { }
|
||||
updateBubble();
|
||||
}
|
||||
|
||||
private void removeBubbleByUser() {
|
||||
Settings.bubble = false;
|
||||
Settings.save();
|
||||
hideBubble();
|
||||
}
|
||||
|
||||
private void hideBubble() {
|
||||
if (bubble != null && wm != null) {
|
||||
try { wm.removeView(bubble); } catch (RuntimeException ignored) { }
|
||||
}
|
||||
bubble = null;
|
||||
hideRemoveZone();
|
||||
}
|
||||
|
||||
// ---- remove zone (the drop target at the bottom) ----
|
||||
|
||||
private void showRemoveZone() {
|
||||
if (removeZone != null || wm == null) return;
|
||||
int zs = dp(64);
|
||||
TextView z = new TextView(this);
|
||||
z.setText("✕");
|
||||
z.setTextColor(Color.WHITE);
|
||||
z.setGravity(Gravity.CENTER);
|
||||
z.setTextSize(22f);
|
||||
z.setWidth(zs);
|
||||
z.setHeight(zs);
|
||||
z.setBackground(removeZoneBg(false));
|
||||
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
|
||||
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
|
||||
bubbleLp.type,
|
||||
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
|
||||
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
|
||||
PixelFormat.TRANSLUCENT);
|
||||
lp.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
|
||||
lp.y = dp(48);
|
||||
try { wm.addView(z, lp); removeZone = z; } catch (RuntimeException e) { removeZone = null; }
|
||||
}
|
||||
|
||||
private void hideRemoveZone() {
|
||||
if (removeZone != null && wm != null) {
|
||||
try { wm.removeView(removeZone); } catch (RuntimeException ignored) { }
|
||||
}
|
||||
removeZone = null;
|
||||
}
|
||||
|
||||
private void highlightRemoveZone(boolean over) {
|
||||
if (removeZone instanceof TextView) {
|
||||
removeZone.setBackground(removeZoneBg(over));
|
||||
((TextView) removeZone).setScaleX(over ? 1.25f : 1f);
|
||||
((TextView) removeZone).setScaleY(over ? 1.25f : 1f);
|
||||
}
|
||||
}
|
||||
|
||||
private GradientDrawable removeZoneBg(boolean over) {
|
||||
GradientDrawable g = new GradientDrawable();
|
||||
g.setShape(GradientDrawable.OVAL);
|
||||
g.setColor(over ? 0xFFC62828 : 0xCC424242);
|
||||
g.setStroke(dp(2), 0xCCFFFFFF);
|
||||
return g;
|
||||
}
|
||||
|
||||
/** True when the bubble's centre is over the bottom remove zone. */
|
||||
private boolean overRemoveZone() {
|
||||
if (removeZone == null) return false;
|
||||
android.util.DisplayMetrics dm = getResources().getDisplayMetrics();
|
||||
float bx = bubbleLp.x + bubbleSize / 2f;
|
||||
float by = bubbleLp.y + bubbleSize / 2f;
|
||||
float zx = dm.widthPixels / 2f;
|
||||
float zy = dm.heightPixels - dp(48) - dp(32); // zone centre (bottom margin + half height)
|
||||
float dx = bx - zx, dy = by - zy;
|
||||
return Math.sqrt(dx * dx + dy * dy) < dp(80);
|
||||
}
|
||||
|
||||
private GradientDrawable bubbleBg(boolean driverOn) {
|
||||
GradientDrawable g = new GradientDrawable();
|
||||
g.setShape(GradientDrawable.OVAL);
|
||||
// blue = Steam Native Hook-up, green = SDL3 driver on, red = off
|
||||
g.setColor(!driverOn ? 0xFFC62828 : Settings.isHookup() ? 0xFF1565C0 : 0xFF2E7D32);
|
||||
g.setStroke(dp(2), 0xCCFFFFFF);
|
||||
return g;
|
||||
}
|
||||
|
||||
private void updateBubble() {
|
||||
if (bubble == null) return;
|
||||
main.post(() -> {
|
||||
if (bubble == null) return;
|
||||
bubble.setBackground(bubbleBg(Settings.driverEnabled));
|
||||
bubble.setText(Settings.isHookup() ? "HOOK" : "SDL3");
|
||||
});
|
||||
}
|
||||
|
||||
private int dp(int v) {
|
||||
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, v, getResources().getDisplayMetrics());
|
||||
}
|
||||
|
||||
// ---------- client -> controller ----------
|
||||
|
||||
/** Applies the touchpad swap / invert settings to one trackpad's [down, x, y]. */
|
||||
private static void orient(float[] p, int player) {
|
||||
if (Settings.touchSwap[player]) { float t = p[1]; p[1] = p[2]; p[2] = t; }
|
||||
if (Settings.touchInvX[player]) p[1] = -p[1];
|
||||
if (Settings.touchInvY[player]) p[2] = -p[2];
|
||||
}
|
||||
|
||||
private void mergeOutput(Bundle b) {
|
||||
if (b == null) return;
|
||||
if (b.containsKey("rl") || b.containsKey("rr")) {
|
||||
NativeBridge.setRumble(b.getInt("slot", 0), clamp(b.getInt("rl")), clamp(b.getInt("rr")));
|
||||
}
|
||||
// A client that sets the lightbar overrides the saved colour until the bridge screen changes it again.
|
||||
if (b.containsKey("r") || b.containsKey("g") || b.containsKey("b")) {
|
||||
int ps = Math.max(0, Math.min(Settings.PLAYERS - 1, b.getInt("slot", 0)));
|
||||
if (b.containsKey("r")) Settings.lightR[ps] = clamp(b.getInt("r"));
|
||||
if (b.containsKey("g")) Settings.lightG[ps] = clamp(b.getInt("g"));
|
||||
if (b.containsKey("b")) Settings.lightB[ps] = clamp(b.getInt("b"));
|
||||
NativeBridge.applyOutput(ps);
|
||||
}
|
||||
}
|
||||
|
||||
private static int clamp(int v) { return Math.max(0, Math.min(255, v)); }
|
||||
|
||||
// ---------- controller -> clients ----------
|
||||
|
||||
// A frame goes to DroidDeck only when the controller state changed (and for FRAME_SETTLE_MS after a change, so
|
||||
// DroidDeck's stick throttle always gets the final position), plus a keep-alive every FRAME_KEEPALIVE_MS. The
|
||||
// loop runs at up to 1000 Hz but most controllers report at 250-500 Hz, and an idle controller not at all:
|
||||
// sending every pass only fills DroidDeck's queue with copies.
|
||||
private static final long FRAME_SETTLE_MS = 20, FRAME_KEEPALIVE_MS = 100;
|
||||
private final float[][] lastFrame = new float[NativeBridge.MAX_PADS][];
|
||||
private final long[] lastFrameChangeMs = new long[NativeBridge.MAX_PADS], lastFrameSentMs = new long[NativeBridge.MAX_PADS];
|
||||
|
||||
private boolean frameWorthSending(float[] f, int slot) {
|
||||
if (slot < 0 || slot >= NativeBridge.MAX_PADS) return true;
|
||||
long now = SystemClock.uptimeMillis();
|
||||
float[] last = lastFrame[slot];
|
||||
if (last == null || last.length != f.length) last = lastFrame[slot] = new float[f.length];
|
||||
if (!java.util.Arrays.equals(f, last)) {
|
||||
System.arraycopy(f, 0, last, 0, f.length); // f is native's reused array: keep a copy
|
||||
lastFrameChangeMs[slot] = now;
|
||||
} else if (now - lastFrameChangeMs[slot] > FRAME_SETTLE_MS && now - lastFrameSentMs[slot] < FRAME_KEEPALIVE_MS) {
|
||||
return false;
|
||||
}
|
||||
lastFrameSentMs[slot] = now;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override public void onFrame(float[] f, int slot) {
|
||||
if (slot >= 0 && slot < NativeBridge.MAX_PADS && f.length >= NativeBridge.FRAME_LEN) {
|
||||
lastBattery[slot] = (int) f[19];
|
||||
calibrationSample(f, slot);
|
||||
}
|
||||
if (clients.isEmpty() || f.length < NativeBridge.FRAME_LEN) return;
|
||||
if (!frameWorthSending(f, slot)) return;
|
||||
Bundle b = new Bundle();
|
||||
b.putByteArray("raw", new byte[0]);
|
||||
b.putLong("t", SystemClock.elapsedRealtimeNanos());
|
||||
int rawMask = (int) f[0];
|
||||
int mask2 = f.length >= 22 ? (int) f[21] : 0; // extra buttons (MISC2..6, e.g. Flydigi C/Z)
|
||||
int mask = Settings.applyGripRemap(rawMask, mask2, slot); // user button -> L4/R4/L5/R5
|
||||
b.putInt("mask", mask);
|
||||
b.putInt("lx", (int) f[1]); b.putInt("ly", (int) f[2]);
|
||||
b.putInt("rx", (int) f[3]); b.putInt("ry", (int) f[4]);
|
||||
b.putInt("l2", (int) f[5]); b.putInt("r2", (int) f[6]);
|
||||
float gk = Settings.gyroGain[slot] / 100f;
|
||||
int inv = Settings.gyroInvert[slot];
|
||||
float dz = Settings.gyroDeadzone[slot];
|
||||
float[] bias = Settings.gyroBias[slot];
|
||||
int[] gmap = Settings.gyroMap[slot];
|
||||
boolean accFollows = Settings.accelFollows[slot];
|
||||
float[] gy = {f[7] * RAD_TO_DEG, f[8] * RAD_TO_DEG, f[9] * RAD_TO_DEG}; // deg/s
|
||||
float[] ac = {f[10] / G, f[11] / G, f[12] / G}; // g
|
||||
for (int k = 0; k < 3; k++) {
|
||||
gy[k] -= bias[k]; // remove resting drift (from Calibrate)
|
||||
if (Math.abs(gy[k]) < dz) gy[k] = 0f; // deadzone, in real deg/s (before gain)
|
||||
}
|
||||
float[] go = new float[3], ao = new float[3];
|
||||
for (int i = 0; i < 3; i++) {
|
||||
float sign = (inv & (1 << i)) != 0 ? -1f : 1f;
|
||||
int src = gmap[i];
|
||||
go[i] = gy[src] * gk * sign;
|
||||
ao[i] = accFollows ? ac[src] * sign : ac[i];
|
||||
}
|
||||
// Sony family only (DualShock 4 = 3, DualSense = 4, DualSense Edge = 5): their report has ONE
|
||||
// full-width multitouch pad and remaps the IMU axes (X, Z, -Y) vs the Deck IMU. The Steam Deck (0)
|
||||
// and Steam Controller (1) have two trackpads and use the Deck IMU convention, so they are left as-is.
|
||||
int presentType = Settings.PRESENT_PAD_TYPE[Settings.presentAs];
|
||||
boolean sony = Settings.isSonyPadType(presentType);
|
||||
if (sony) {
|
||||
float tg = go[1]; go[1] = -go[2]; go[2] = tg;
|
||||
float ta = ao[1]; ao[1] = -ao[2]; ao[2] = ta;
|
||||
}
|
||||
b.putFloatArray("gyro", go);
|
||||
b.putFloatArray("accel", ao);
|
||||
|
||||
|
||||
// Raw fingers (kept for older clients) ...
|
||||
List<Integer> t = new ArrayList<>();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
if (f[13 + 3 * i] > 0.5f) { t.add(i + 1); t.add((int) f[14 + 3 * i]); t.add((int) f[15 + 3 * i]); }
|
||||
}
|
||||
int[] touch = new int[t.size()];
|
||||
for (int i = 0; i < touch.length; i++) touch[i] = t.get(i);
|
||||
b.putIntArray("touch", touch);
|
||||
|
||||
// ... and the decoupled version: each half is its own trackpad with local -1..1 coordinates.
|
||||
float[] padL = new float[3], padR = new float[3];
|
||||
int mode = Settings.touchMode[slot];
|
||||
// A 2015 Steam Controller has two real trackpads: always split the touchpad into left/right halves.
|
||||
if (presentType == Settings.PAD_TYPE_STEAM_2015 && mode != Settings.TOUCH_OFF) mode = Settings.TOUCH_SPLIT;
|
||||
// A native Sony pad (DualShock 4, DualSense, DualSense Edge) has ONE full-width multitouch
|
||||
// surface, so ignore the Deck split there: keep SDL's finger slots (finger 0 is the primary
|
||||
// touch the game tracks) and map both across the whole pad. padL carries finger 0, padR finger 1.
|
||||
// Only the Steam Deck pad (type 0) keeps the left/right split, since it has two real trackpads.
|
||||
if (mode != Settings.TOUCH_OFF) {
|
||||
if (sony) {
|
||||
for (int i = 0; i < 2; i++) {
|
||||
if (f[13 + 3 * i] <= 0.5f) continue;
|
||||
float[] p = (i == 0) ? padL : padR;
|
||||
p[0] = 1f; p[1] = f[14 + 3 * i] / PAD_W * 2f - 1f; p[2] = f[15 + 3 * i] / PAD_H * 2f - 1f;
|
||||
}
|
||||
} else for (int i = 0; i < 2; i++) {
|
||||
if (f[13 + 3 * i] <= 0.5f) continue;
|
||||
float x = f[14 + 3 * i], y = f[15 + 3 * i];
|
||||
float ny = y / PAD_H * 2f - 1f;
|
||||
if (mode == Settings.TOUCH_SINGLE) {
|
||||
if (padR[0] == 0f) { padR[0] = 1f; padR[1] = x / PAD_W * 2f - 1f; padR[2] = ny; }
|
||||
} else if (x < PAD_W / 2f) {
|
||||
if (padL[0] == 0f) { padL[0] = 1f; padL[1] = x / (PAD_W / 2f) * 2f - 1f; padL[2] = ny; }
|
||||
} else {
|
||||
if (padR[0] == 0f) { padR[0] = 1f; padR[1] = (x - PAD_W / 2f) / (PAD_W / 2f) * 2f - 1f; padR[2] = ny; }
|
||||
}
|
||||
}
|
||||
}
|
||||
int click = -1; // -1 none, 0 left trackpad, 1 right trackpad
|
||||
if (((mask >> 13) & 1) != 0 && mode != Settings.TOUCH_OFF) {
|
||||
click = (mode == Settings.TOUCH_SPLIT && padL[0] > 0f && padR[0] == 0f) ? 0 : 1;
|
||||
}
|
||||
// Button -> trackpad touch / click remaps (targets 4..7)
|
||||
int[] rm = Settings.remap[slot];
|
||||
if (Settings.srcDown(rawMask, mask2, rm[6]) && padL[0] == 0f) { padL[0] = 1f; padL[1] = 0f; padL[2] = 0f; }
|
||||
if (Settings.srcDown(rawMask, mask2, rm[7]) && padR[0] == 0f) { padR[0] = 1f; padR[1] = 0f; padR[2] = 0f; }
|
||||
if (Settings.srcDown(rawMask, mask2, rm[4])) { if (padL[0] == 0f) padL[0] = 1f; click = 0; }
|
||||
if (Settings.srcDown(rawMask, mask2, rm[5])) { if (padR[0] == 0f) padR[0] = 1f; click = 1; }
|
||||
orient(padL, slot);
|
||||
orient(padR, slot);
|
||||
b.putFloatArray("padL", padL);
|
||||
b.putFloatArray("padR", padR);
|
||||
b.putInt("padClick", click);
|
||||
|
||||
int state = (int) f[20];
|
||||
b.putInt("slot", slot);
|
||||
b.putInt("ptype", Settings.PRESENT_PAD_TYPE[Settings.presentAs]);
|
||||
b.putInt("vid", NativeBridge.vids[slot]);
|
||||
b.putInt("pid", NativeBridge.pids[slot]);
|
||||
b.putInt("battery", Math.max(0, (int) f[19]));
|
||||
b.putString("charge", state == 3 ? "charging" : state == 4 ? "full" : state == 1 ? "discharging" : "unknown");
|
||||
for (Messenger c : clients) {
|
||||
try {
|
||||
Message m = Message.obtain(null, MSG_FRAME);
|
||||
m.setData(b);
|
||||
c.send(m);
|
||||
} catch (RemoteException e) { clients.remove(c); clientCount = clients.size(); }
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onPadGone(int slot) {
|
||||
for (Messenger c : clients) {
|
||||
try {
|
||||
Bundle b = new Bundle();
|
||||
b.putInt("slot", slot);
|
||||
Message m = Message.obtain(null, MSG_PAD_GONE);
|
||||
m.setData(b);
|
||||
c.send(m);
|
||||
} catch (RemoteException e) { clients.remove(c); }
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Steam Controller (2026) raw passthrough -> clients ----------
|
||||
@Override public void onTritonState(int reportId, byte[] payload) {
|
||||
if (clients.isEmpty() || payload == null) return;
|
||||
Bundle b = new Bundle();
|
||||
b.putInt("id", reportId);
|
||||
b.putByteArray("data", payload);
|
||||
sendAll(MSG_TRITON_STATE, b);
|
||||
}
|
||||
|
||||
@Override public void onTritonConnected(boolean on, String what) {
|
||||
for (Messenger c : clients) sendTritonConn(c, on, what);
|
||||
}
|
||||
|
||||
@Override public void onTritonFeature(long request, byte[] report) {
|
||||
Bundle b = new Bundle();
|
||||
b.putLong("request", request);
|
||||
if (report != null) b.putByteArray("data", report);
|
||||
sendAll(MSG_TRITON_FEATURE, b);
|
||||
}
|
||||
|
||||
private void sendTritonConn(Messenger c, boolean on, String what) {
|
||||
try {
|
||||
Bundle b = new Bundle();
|
||||
b.putBoolean("on", on);
|
||||
b.putString("what", what);
|
||||
Message m = Message.obtain(null, MSG_TRITON_CONN);
|
||||
m.setData(b);
|
||||
c.send(m);
|
||||
} catch (RemoteException e) { clients.remove(c); clientCount = clients.size(); }
|
||||
}
|
||||
|
||||
/** SDL3's loop must run for controllers to work: it runs in this service, no screen needed. */
|
||||
private void ensureBridgeLoop() {
|
||||
SdlEngine.start(this);
|
||||
}
|
||||
|
||||
// ---------- Steam Native Hook-up -> clients ----------
|
||||
@Override public void onHookupAdded(int slot, Bundle identity) { sendAll(MSG_HOOKUP_ADD, identity); }
|
||||
|
||||
@Override public void onHookupInput(int slot, byte[] report) {
|
||||
if (clients.isEmpty() || report == null) return;
|
||||
Bundle b = new Bundle();
|
||||
b.putInt("slot", slot);
|
||||
b.putByteArray("data", report);
|
||||
sendAll(MSG_HOOKUP_INPUT, b);
|
||||
}
|
||||
|
||||
@Override public void onBridgeLog(String line) {
|
||||
Bundle b = new Bundle();
|
||||
b.putString("text", line);
|
||||
sendAll(MSG_BRIDGE_LOG, b);
|
||||
}
|
||||
|
||||
@Override public void onHookupRemoved(int slot) {
|
||||
Bundle b = new Bundle();
|
||||
b.putInt("slot", slot);
|
||||
sendAll(MSG_HOOKUP_REMOVE, b);
|
||||
}
|
||||
|
||||
@Override public void onHookupReply(int slot, long request, byte[] report) {
|
||||
Bundle b = new Bundle();
|
||||
b.putInt("slot", slot);
|
||||
b.putLong("request", request);
|
||||
if (report != null) b.putByteArray("data", report);
|
||||
sendAll(MSG_HOOKUP_REPLY, b);
|
||||
}
|
||||
|
||||
// ---------- DroidDeck's SDL3Bridge settings tab ----------
|
||||
private final int[] lastBattery = { -1, -1, -1, -1 };
|
||||
|
||||
// Gyro calibration started from DroidDeck: averages the resting gyro of that player's own controller.
|
||||
private static final int CALIB_SAMPLES = 180; // ~0.7 s at 4 ms per frame
|
||||
private final Object calibLock = new Object();
|
||||
private int calibPlayer = -1, calibCount;
|
||||
private final float[] calibSum = new float[3];
|
||||
|
||||
private void startCalibration(int p) {
|
||||
synchronized (calibLock) { calibPlayer = p; calibCount = 0; calibSum[0] = calibSum[1] = calibSum[2] = 0f; }
|
||||
}
|
||||
|
||||
private void calibrationSample(float[] f, int slot) {
|
||||
synchronized (calibLock) {
|
||||
if (calibPlayer != slot) return;
|
||||
calibSum[0] += f[7]; calibSum[1] += f[8]; calibSum[2] += f[9];
|
||||
if (++calibCount < CALIB_SAMPLES) return;
|
||||
float[] b = Settings.gyroBias[slot];
|
||||
for (int k = 0; k < 3; k++) b[k] = calibSum[k] / CALIB_SAMPLES * RAD_TO_DEG;
|
||||
calibPlayer = -1;
|
||||
}
|
||||
Settings.save();
|
||||
}
|
||||
|
||||
/** Everything the tab shows: settings, their choices (so DroidDeck needs no copy of them) and live status. */
|
||||
private Bundle settingsSnapshot() {
|
||||
Bundle b = new Bundle();
|
||||
b.putInt("v", 1);
|
||||
b.putString("status", NativeBridge.lastStatus);
|
||||
b.putBoolean("overlayAllowed", android.provider.Settings.canDrawOverlays(this));
|
||||
b.putBoolean("notifications", getSystemService(NotificationManager.class).areNotificationsEnabled());
|
||||
b.putString("engineError", SdlEngine.error == null ? "" : SdlEngine.error);
|
||||
b.putString("engineMode", SdlEngine.mode);
|
||||
b.putBoolean("fastPath", NativeBridge.hookupShmInode() != 0);
|
||||
b.putString("triton", NativeBridge.tritonConnected ? NativeBridge.tritonWhat : "");
|
||||
String[] padNames = new String[NativeBridge.MAX_PADS], padIds = new String[NativeBridge.MAX_PADS];
|
||||
String[] hookNames = new String[NativeBridge.MAX_PADS], hookIds = new String[NativeBridge.MAX_PADS];
|
||||
for (int i = 0; i < NativeBridge.MAX_PADS; i++) {
|
||||
String n = NativeBridge.names[i];
|
||||
padNames[i] = n == null ? "" : n;
|
||||
padIds[i] = n == null ? "" : String.format("%04x:%04x", NativeBridge.vids[i], NativeBridge.pids[i]);
|
||||
Bundle h = NativeBridge.hookupIdentity[i];
|
||||
hookNames[i] = h == null ? "" : h.getString("name", "");
|
||||
hookIds[i] = h == null ? "" : String.format("%04x:%04x", h.getInt("vid"), h.getInt("pid"));
|
||||
}
|
||||
b.putStringArray("padNames", padNames);
|
||||
b.putStringArray("padIds", padIds);
|
||||
b.putIntArray("padBattery", lastBattery.clone());
|
||||
b.putStringArray("hookNames", hookNames);
|
||||
b.putStringArray("hookIds", hookIds);
|
||||
synchronized (calibLock) { b.putInt("calibrating", calibPlayer); }
|
||||
// global settings
|
||||
b.putInt("presentAs", Settings.presentAs);
|
||||
b.putBoolean("driverEnabled", Settings.driverEnabled);
|
||||
b.putBoolean("forceUsb", Settings.forceUsb);
|
||||
b.putInt("pollMs", Settings.pollMs);
|
||||
b.putBoolean("bubble", Settings.bubble);
|
||||
// choices
|
||||
b.putStringArray("presentNames", Settings.PRESENT_NAMES);
|
||||
b.putStringArray("rateNames", Settings.RATE_NAMES);
|
||||
b.putIntArray("rateMs", Settings.RATE_MS);
|
||||
b.putStringArray("touchNames", Settings.TOUCH_NAMES);
|
||||
b.putStringArray("srcNames", Settings.SRC_NAMES);
|
||||
b.putStringArray("remapTargets", Settings.REMAP_TARGETS);
|
||||
b.putStringArray("axisNames", Settings.AXIS_NAMES);
|
||||
b.putStringArray("gyroInvNames", Settings.GYRO_INV_NAMES);
|
||||
b.putStringArray("playerLedNames", Settings.PLAYER_NAMES);
|
||||
// per player (index p, or p * n + i for the ones with several entries)
|
||||
int P = Settings.PLAYERS;
|
||||
int[] gyroMap = new int[P * 3], remap = new int[P * Settings.REMAP_COUNT];
|
||||
float[] bias = new float[P * 3];
|
||||
for (int p = 0; p < P; p++) {
|
||||
for (int i = 0; i < 3; i++) { gyroMap[p * 3 + i] = Settings.gyroMap[p][i]; bias[p * 3 + i] = Settings.gyroBias[p][i]; }
|
||||
for (int i = 0; i < Settings.REMAP_COUNT; i++) remap[p * Settings.REMAP_COUNT + i] = Settings.remap[p][i];
|
||||
}
|
||||
b.putIntArray("touchMode", Settings.touchMode.clone());
|
||||
b.putBooleanArray("touchInvX", Settings.touchInvX.clone());
|
||||
b.putBooleanArray("touchInvY", Settings.touchInvY.clone());
|
||||
b.putBooleanArray("touchSwap", Settings.touchSwap.clone());
|
||||
b.putIntArray("gyroGain", Settings.gyroGain.clone());
|
||||
b.putIntArray("gyroInvert", Settings.gyroInvert.clone());
|
||||
b.putIntArray("gyroDeadzone", Settings.gyroDeadzone.clone());
|
||||
b.putIntArray("gyroMap", gyroMap);
|
||||
b.putFloatArray("gyroBias", bias);
|
||||
b.putBooleanArray("accelFollows", Settings.accelFollows.clone());
|
||||
b.putIntArray("remap", remap);
|
||||
b.putIntArray("lightR", Settings.lightR.clone());
|
||||
b.putIntArray("lightG", Settings.lightG.clone());
|
||||
b.putIntArray("lightB", Settings.lightB.clone());
|
||||
b.putIntArray("brightness", Settings.brightness.clone());
|
||||
b.putIntArray("playerLed", Settings.playerLed.clone());
|
||||
return b;
|
||||
}
|
||||
|
||||
private static int clampInt(int v, int lo, int hi) { return Math.max(lo, Math.min(hi, v)); }
|
||||
|
||||
/** One change from DroidDeck's tab, with the same effect as the same change on this app's own screen. */
|
||||
private void applyRemote(Bundle d) {
|
||||
if (d == null) return;
|
||||
String key = d.getString("key", "");
|
||||
int p = clampInt(d.getInt("p", 0), 0, Settings.PLAYERS - 1);
|
||||
int i = d.getInt("i", 0);
|
||||
int v = d.getInt("int", 0);
|
||||
boolean on = d.getBoolean("bool", false);
|
||||
switch (key) {
|
||||
case "presentAs":
|
||||
Settings.presentAs = clampInt(v, 0, Settings.PRESENT_NAMES.length - 1);
|
||||
if (!Settings.isHookup()) Settings.lastPresentAs = Settings.presentAs;
|
||||
Settings.save();
|
||||
NativeBridge.applyHookup();
|
||||
updateBubble();
|
||||
break;
|
||||
case "driverEnabled":
|
||||
if (Settings.driverEnabled != on) toggleDriver();
|
||||
break;
|
||||
case "forceUsb":
|
||||
Settings.forceUsb = on;
|
||||
Settings.save();
|
||||
NativeBridge.applyForce();
|
||||
break;
|
||||
case "pollMs":
|
||||
Settings.pollMs = clampInt(v, 1, 16);
|
||||
Settings.save();
|
||||
NativeBridge.applyRate();
|
||||
break;
|
||||
case "bubble":
|
||||
if (on && !android.provider.Settings.canDrawOverlays(this)) break; // needs the permission first
|
||||
Settings.bubble = on;
|
||||
Settings.save();
|
||||
if (on) showBubble(); else hideBubble();
|
||||
break;
|
||||
case "touchMode": Settings.touchMode[p] = clampInt(v, 0, 2); Settings.save(); break;
|
||||
case "touchInvX": Settings.touchInvX[p] = on; Settings.save(); break;
|
||||
case "touchInvY": Settings.touchInvY[p] = on; Settings.save(); break;
|
||||
case "touchSwap": Settings.touchSwap[p] = on; Settings.save(); break;
|
||||
case "gyroGain": Settings.gyroGain[p] = clampInt(v, 1, 800); Settings.save(); break;
|
||||
case "gyroInvert": Settings.gyroInvert[p] = clampInt(v, 0, 7); Settings.save(); break;
|
||||
case "gyroDeadzone": Settings.gyroDeadzone[p] = clampInt(v, 0, 50); Settings.save(); break;
|
||||
case "gyroMap":
|
||||
if (i >= 0 && i < 3) { Settings.gyroMap[p][i] = clampInt(v, 0, 2); Settings.save(); }
|
||||
break;
|
||||
case "accelFollows": Settings.accelFollows[p] = on; Settings.save(); break;
|
||||
case "remap":
|
||||
if (i >= 0 && i < Settings.REMAP_COUNT) { Settings.remap[p][i] = clampInt(v, 0, Settings.SRC_NAMES.length - 1); Settings.save(); }
|
||||
break;
|
||||
case "lightR": Settings.lightR[p] = clampInt(v, 0, 255); Settings.save(); NativeBridge.applyOutput(p); break;
|
||||
case "lightG": Settings.lightG[p] = clampInt(v, 0, 255); Settings.save(); NativeBridge.applyOutput(p); break;
|
||||
case "lightB": Settings.lightB[p] = clampInt(v, 0, 255); Settings.save(); NativeBridge.applyOutput(p); break;
|
||||
case "brightness": Settings.brightness[p] = clampInt(v, 0, 100); Settings.save(); NativeBridge.applyOutput(p); break;
|
||||
case "playerLed": Settings.playerLed[p] = clampInt(v, 0, 4); Settings.save(); NativeBridge.applyOutput(p); break;
|
||||
case "calibrate": startCalibration(p); break;
|
||||
case "resetCalibration":
|
||||
synchronized (calibLock) { if (calibPlayer == p) calibPlayer = -1; }
|
||||
Settings.gyroBias[p][0] = Settings.gyroBias[p][1] = Settings.gyroBias[p][2] = 0f;
|
||||
Settings.save();
|
||||
break;
|
||||
default:
|
||||
android.util.Log.w("SDL3Bridge", "settings: unknown key from DroidDeck: " + key);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendOne(Messenger c, int what, Bundle b) {
|
||||
try {
|
||||
Message m = Message.obtain(null, what);
|
||||
m.setData(b);
|
||||
c.send(m);
|
||||
} catch (RemoteException e) { clients.remove(c); clientCount = clients.size(); }
|
||||
}
|
||||
|
||||
private void sendAll(int what, Bundle b) {
|
||||
for (Messenger c : clients) {
|
||||
try {
|
||||
Message m = Message.obtain(null, what);
|
||||
m.setData(b);
|
||||
c.send(m);
|
||||
} catch (RemoteException e) { clients.remove(c); clientCount = clients.size(); }
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onStatus(String s) {
|
||||
connectedState = s != null && s.startsWith("Connected");
|
||||
updateBubble();
|
||||
main.post(() -> refreshNotification(s));
|
||||
for (Messenger c : clients) sendStatus(c, s);
|
||||
}
|
||||
|
||||
private void sendStatus(Messenger c, String s) {
|
||||
try {
|
||||
Bundle b = new Bundle();
|
||||
b.putString("text", s);
|
||||
Message m = Message.obtain(null, MSG_STATUS);
|
||||
m.setData(b);
|
||||
c.send(m);
|
||||
} catch (RemoteException e) { clients.remove(c); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.RectF;
|
||||
import android.view.View;
|
||||
|
||||
/**
|
||||
* Universal live gamepad diagram for any SDL3 controller (DualSense / Edge, Xbox, Switch Pro,
|
||||
* Steam Controller 2015 & 2026, generic pads). It draws only the controls the controller actually
|
||||
* reports (via NativeBridge caps) and labels the face / menu buttons for the controller kind.
|
||||
*
|
||||
* Orange = held now, green = pressed at least once (works), grey = present but untested.
|
||||
*/
|
||||
public class ControllerView extends View {
|
||||
private static final int ORANGE = 0xFFFF9800, GREEN = 0xFF2E7D32, GRAY = 0xFF37474F, LINE = 0xFF90A4AE;
|
||||
|
||||
// frame-mask bit numbers
|
||||
private static final int B_SOUTH = 0, B_EAST = 1, B_WEST = 2, B_NORTH = 3, B_L1 = 4, B_R1 = 5,
|
||||
B_L2 = 6, B_R2 = 7, B_BACK = 8, B_START = 9, B_L3 = 10, B_R3 = 11, B_GUIDE = 12,
|
||||
B_TOUCH = 13, B_MISC = 14, B_UP = 15, B_DOWN = 16, B_LEFT = 17, B_RIGHT = 18,
|
||||
B_P1 = 19, B_P2 = 20, B_P3 = 21, B_P4 = 22;
|
||||
|
||||
// tested-flag bits (not button bits)
|
||||
private static final int T_LS = 1, T_RS = 2, T_L2 = 4, T_R2 = 8, T_GYRO = 16, T_ACCEL = 32, T_TOUCH = 64;
|
||||
|
||||
private final Paint fill = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final Paint stroke = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final Paint text = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final RectF rect = new RectF();
|
||||
|
||||
private volatile float[] frame = new float[NativeBridge.FRAME_LEN];
|
||||
private volatile int mask;
|
||||
private volatile int testedButtons;
|
||||
private volatile int testedFlags;
|
||||
private volatile boolean connected;
|
||||
private long lastInvalidate;
|
||||
|
||||
// capabilities (default: assume everything until the controller reports otherwise)
|
||||
private volatile int present = (1 << 23) - 1;
|
||||
private volatile int axes = 0xF;
|
||||
private volatile int touchpads = 1;
|
||||
private volatile String kind = "generic";
|
||||
|
||||
public ControllerView(Context c) {
|
||||
super(c);
|
||||
setBackgroundColor(0xFF111111);
|
||||
stroke.setStyle(Paint.Style.STROKE);
|
||||
stroke.setStrokeWidth(0.5f);
|
||||
text.setTextAlign(Paint.Align.CENTER);
|
||||
text.setColor(0xFFECEFF1);
|
||||
frame[1] = frame[2] = frame[3] = frame[4] = 128f;
|
||||
}
|
||||
|
||||
/** Capabilities of the displayed controller, from the native layer. */
|
||||
public void setCaps(int present, int axes, int touchpads, String kind) {
|
||||
this.present = present;
|
||||
this.axes = axes;
|
||||
this.touchpads = touchpads;
|
||||
this.kind = kind == null ? "generic" : kind;
|
||||
postInvalidate();
|
||||
}
|
||||
|
||||
/** Called from any thread with each native frame. */
|
||||
public void update(float[] f) {
|
||||
if (f == null || f.length < NativeBridge.FRAME_LEN) return;
|
||||
float[] c = f.clone();
|
||||
frame = c;
|
||||
connected = true;
|
||||
int m = (int) c[0];
|
||||
mask = m;
|
||||
testedButtons |= m;
|
||||
int t = testedFlags;
|
||||
if (Math.abs(c[1] - 128f) > 60f || Math.abs(c[2] - 128f) > 60f) t |= T_LS;
|
||||
if (Math.abs(c[3] - 128f) > 60f || Math.abs(c[4] - 128f) > 60f) t |= T_RS;
|
||||
if (c[5] > 100f) t |= T_L2;
|
||||
if (c[6] > 100f) t |= T_R2;
|
||||
if (Math.abs(c[7]) + Math.abs(c[8]) + Math.abs(c[9]) > 0.6f) t |= T_GYRO;
|
||||
if (Math.abs(c[10]) + Math.abs(c[11]) + Math.abs(c[12]) > 3f) t |= T_ACCEL;
|
||||
if (c[13] > 0.5f || c[16] > 0.5f) t |= T_TOUCH;
|
||||
testedFlags = t;
|
||||
long now = System.nanoTime();
|
||||
if (now - lastInvalidate > 16_000_000L) {
|
||||
lastInvalidate = now;
|
||||
postInvalidate();
|
||||
}
|
||||
}
|
||||
|
||||
public void setDisconnected() { connected = false; mask = 0; postInvalidate(); }
|
||||
|
||||
public void resetTested() { testedButtons = 0; testedFlags = 0; postInvalidate(); }
|
||||
|
||||
/** One-line summary of what has been verified so far (only counts controls the pad has). */
|
||||
public String summary() {
|
||||
int p = present & ((1 << 23) - 1);
|
||||
int n = Integer.bitCount(p);
|
||||
int done = Integer.bitCount(testedButtons & p);
|
||||
int t = testedFlags;
|
||||
StringBuilder sb = new StringBuilder("Tested: buttons ").append(done).append('/').append(n);
|
||||
if ((axes & 1) != 0 || (axes & 2) != 0) sb.append(" sticks ").append(mark(stickOk(t)));
|
||||
if ((axes & 12) != 0) sb.append(" triggers ").append(mark(trigOk(t)));
|
||||
sb.append(" gyro ").append(mark((t & T_GYRO) != 0));
|
||||
sb.append(" accel ").append(mark((t & T_ACCEL) != 0));
|
||||
if (touchpads > 0) sb.append(" touchpad ").append(mark((t & T_TOUCH) != 0));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private boolean stickOk(int t) {
|
||||
boolean l = (axes & 1) == 0 || (t & T_LS) != 0;
|
||||
boolean r = (axes & 2) == 0 || (t & T_RS) != 0;
|
||||
return l && r;
|
||||
}
|
||||
|
||||
private boolean trigOk(int t) {
|
||||
boolean l = (axes & 4) == 0 || (t & T_L2) != 0;
|
||||
boolean r = (axes & 8) == 0 || (t & T_R2) != 0;
|
||||
return l && r;
|
||||
}
|
||||
|
||||
private static String mark(boolean ok) { return ok ? "OK" : "-"; }
|
||||
|
||||
@Override protected void onMeasure(int w, int h) {
|
||||
int width = MeasureSpec.getSize(w);
|
||||
setMeasuredDimension(width, (int) (width * 0.82f));
|
||||
}
|
||||
|
||||
// ---------------- labels per controller kind ----------------
|
||||
|
||||
private String[] faceLabels() {
|
||||
switch (kind) {
|
||||
case "ps": return new String[] {"✕", "●", "■", "▲"}; // ✕ ● ■ ▲
|
||||
case "nintendo": return new String[] {"B", "A", "Y", "X"};
|
||||
default: return new String[] {"A", "B", "X", "Y"}; // xbox / steam / generic
|
||||
}
|
||||
}
|
||||
|
||||
private String backLabel() { switch (kind) { case "ps": return "Create"; case "xbox": return "View"; case "nintendo": return "-"; case "steam": return "Back"; default: return "Back"; } }
|
||||
private String startLabel() { switch (kind) { case "ps": return "Options"; case "xbox": return "Menu"; case "nintendo": return "+"; case "steam": return "Start"; default: return "Start"; } }
|
||||
private String guideLabel() { switch (kind) { case "ps": return "PS"; case "nintendo": return "Home"; case "steam": return "Steam"; default: return "Guide"; } }
|
||||
private String miscLabel() { switch (kind) { case "ps": return "Mute"; case "xbox": return "Share"; case "nintendo": return "Capt"; default: return "Misc"; } }
|
||||
|
||||
// ---------------- drawing (100 x 72 unit canvas) ----------------
|
||||
|
||||
private boolean has(int bit) { return ((present >> bit) & 1) != 0; }
|
||||
|
||||
private int col(int bit) {
|
||||
if (((mask >> bit) & 1) != 0) return ORANGE;
|
||||
if (((testedButtons >> bit) & 1) != 0) return GREEN;
|
||||
return GRAY;
|
||||
}
|
||||
|
||||
private void label(Canvas c, String s, float x, float y, float size) {
|
||||
text.setTextSize(size);
|
||||
c.drawText(s, x, y + size * 0.35f, text);
|
||||
}
|
||||
|
||||
/** Rounded rectangle button, drawn only if present. */
|
||||
private void rbtn(Canvas c, float l, float t, float r, float b, int bit, String s) {
|
||||
if (!has(bit)) return;
|
||||
rect.set(l, t, r, b);
|
||||
fill.setColor(col(bit));
|
||||
c.drawRoundRect(rect, 1f, 1f, fill);
|
||||
stroke.setColor(LINE);
|
||||
c.drawRoundRect(rect, 1f, 1f, stroke);
|
||||
if (s != null && !s.isEmpty()) label(c, s, (l + r) / 2f, (t + b) / 2f, 2.2f);
|
||||
}
|
||||
|
||||
private void cbtn(Canvas c, float cx, float cy, float rad, int bit, String s) {
|
||||
if (!has(bit)) return;
|
||||
fill.setColor(col(bit));
|
||||
c.drawCircle(cx, cy, rad, fill);
|
||||
stroke.setColor(LINE);
|
||||
c.drawCircle(cx, cy, rad, stroke);
|
||||
label(c, s, cx, cy, 2.4f);
|
||||
}
|
||||
|
||||
private void meter(Canvas c, float l, float t, float r, float b, float value01, boolean tested) {
|
||||
rect.set(l, t, r, b);
|
||||
fill.setColor(0xFF263238);
|
||||
c.drawRect(rect, fill);
|
||||
rect.set(l, t, l + (r - l) * Math.max(0f, Math.min(1f, value01)), b);
|
||||
fill.setColor(value01 > 0.02f ? ORANGE : (tested ? GREEN : GRAY));
|
||||
c.drawRect(rect, fill);
|
||||
rect.set(l, t, r, b);
|
||||
stroke.setColor(LINE);
|
||||
c.drawRect(rect, stroke);
|
||||
}
|
||||
|
||||
private void stick(Canvas c, float cx, float cy, float x, float y, int clickBit, boolean tested) {
|
||||
boolean clickable = has(clickBit);
|
||||
boolean down = clickable && ((mask >> clickBit) & 1) != 0;
|
||||
stroke.setColor(down ? ORANGE : (tested ? 0xFF66BB6A : LINE));
|
||||
stroke.setStrokeWidth(1f);
|
||||
c.drawCircle(cx, cy, 9f, stroke);
|
||||
stroke.setStrokeWidth(0.5f);
|
||||
fill.setColor(down ? ORANGE : (tested ? GREEN : GRAY));
|
||||
float dx = (x - 128f) / 128f * 6f, dy = (y - 128f) / 128f * 6f;
|
||||
c.drawCircle(cx + dx, cy + dy, 3.6f, fill);
|
||||
}
|
||||
|
||||
@Override protected void onDraw(Canvas c) {
|
||||
super.onDraw(c);
|
||||
float u = getWidth() / 100f;
|
||||
c.save();
|
||||
c.scale(u, u);
|
||||
float[] f = frame;
|
||||
int t = testedFlags;
|
||||
String[] fl = faceLabels();
|
||||
|
||||
// shoulders + triggers
|
||||
if ((axes & 4) != 0) meter(c, 6, 1, 30, 4, f[5] / 255f, (t & T_L2) != 0); else rbtn(c, 6, 1, 30, 4, B_L2, "L2");
|
||||
if ((axes & 8) != 0) meter(c, 70, 1, 94, 4, f[6] / 255f, (t & T_R2) != 0); else rbtn(c, 70, 1, 94, 4, B_R2, "R2");
|
||||
rbtn(c, 6, 5.5f, 30, 10, B_L1, "L1");
|
||||
rbtn(c, 70, 5.5f, 94, 10, B_R1, "R1");
|
||||
|
||||
drawTouchpads(c);
|
||||
|
||||
rbtn(c, 27, 14, 36, 18, B_BACK, backLabel());
|
||||
rbtn(c, 64, 14, 73, 18, B_START, startLabel());
|
||||
rbtn(c, 45, 36, 55, 39.5f, B_MISC, miscLabel());
|
||||
cbtn(c, 50, 44, 2.8f, B_GUIDE, guideLabel());
|
||||
|
||||
// d-pad
|
||||
if (has(B_UP) || has(B_DOWN) || has(B_LEFT) || has(B_RIGHT)) {
|
||||
rbtn(c, 18, 20, 22, 24, B_UP, "");
|
||||
rbtn(c, 18, 32, 22, 36, B_DOWN, "");
|
||||
rbtn(c, 14, 26, 18, 30, B_LEFT, "");
|
||||
rbtn(c, 22, 26, 26, 30, B_RIGHT, "");
|
||||
label(c, "D-pad", 20, 40, 2.2f);
|
||||
}
|
||||
|
||||
// face buttons (diamond): N top, S bottom, W left, E right
|
||||
cbtn(c, 80, 21, 3.2f, B_NORTH, fl[3]);
|
||||
cbtn(c, 80, 35, 3.2f, B_SOUTH, fl[0]);
|
||||
cbtn(c, 73, 28, 3.2f, B_WEST, fl[2]);
|
||||
cbtn(c, 87, 28, 3.2f, B_EAST, fl[1]);
|
||||
|
||||
// sticks
|
||||
if ((axes & 1) != 0) { stick(c, 34, 53, f[1], f[2], B_L3, (t & T_LS) != 0); label(c, has(B_L3) ? "L3" : "L", 34, 64.5f, 2.2f); }
|
||||
if ((axes & 2) != 0) { stick(c, 66, 53, f[3], f[4], B_R3, (t & T_RS) != 0); label(c, has(B_R3) ? "R3" : "R", 66, 64.5f, 2.2f); }
|
||||
|
||||
// paddles / grips
|
||||
rbtn(c, 1.5f, 40, 6.5f, 56, B_P1, "L4");
|
||||
rbtn(c, 93.5f, 40, 98.5f, 56, B_P2, "R4");
|
||||
rbtn(c, 9, 60, 21, 64.5f, B_P3, "L5");
|
||||
rbtn(c, 79, 60, 91, 64.5f, B_P4, "R5");
|
||||
|
||||
// ---- bottom readout strip (own background + divider, clear of the diagram) ----
|
||||
rect.set(0, 66.5f, 100, getHeight() / u);
|
||||
fill.setColor(0xFF0B0E13);
|
||||
c.drawRect(rect, fill);
|
||||
stroke.setColor(0xFF2A3340);
|
||||
c.drawLine(3, 66.5f, 97, 66.5f, stroke);
|
||||
|
||||
String s1 = connected
|
||||
? String.format(java.util.Locale.ROOT, "%s · Gyro %.0f, %.0f, %.0f °/s",
|
||||
kindName(), f[7] * 57.29578f, f[8] * 57.29578f, f[9] * 57.29578f)
|
||||
: "No controller connected";
|
||||
String s2 = connected
|
||||
? String.format(java.util.Locale.ROOT, "Accel %.2f, %.2f, %.2f g · Battery %d%%",
|
||||
f[10] / 9.80665f, f[11] / 9.80665f, f[12] / 9.80665f, (int) Math.max(0f, f[19]))
|
||||
: "";
|
||||
label(c, s1, 50, 71.3f, 2.6f);
|
||||
if (!s2.isEmpty()) label(c, s2, 50, 76.3f, 2.6f);
|
||||
|
||||
c.restore();
|
||||
}
|
||||
|
||||
private String kindName() {
|
||||
switch (kind) {
|
||||
case "ps": return "PlayStation";
|
||||
case "xbox": return "Xbox";
|
||||
case "nintendo": return "Nintendo";
|
||||
case "steam": return "Steam Controller";
|
||||
default: return "Gamepad";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** Draws 0, 1 or 2 trackpads with their finger dots. */
|
||||
private void drawTouchpads(Canvas c) {
|
||||
float[] f = frame;
|
||||
if (touchpads <= 0) {
|
||||
label(c, "no touchpad", 50, 24, 2.2f);
|
||||
return;
|
||||
}
|
||||
if (touchpads >= 2) {
|
||||
padRect(c, 30, 12, 48, 34, "L pad", B_TOUCH);
|
||||
padRect(c, 52, 12, 70, 34, "R pad", B_TOUCH);
|
||||
fingerOnRect(c, 30, 48, 12, 34, 0, 0xFFFFFFFF); // finger slot 0 -> left pad
|
||||
fingerOnRect(c, 52, 70, 12, 34, 1, 0xFF4FC3F7); // finger slot 1 -> right pad
|
||||
return;
|
||||
}
|
||||
// single touchpad
|
||||
padRect(c, 36, 12, 64, 34, null, B_TOUCH);
|
||||
if (Settings.touchMode[0] == Settings.TOUCH_SPLIT) {
|
||||
stroke.setColor(LINE);
|
||||
c.drawLine(50, 12, 50, 34, stroke);
|
||||
label(c, "L pad", 43, 32.5f, 2f);
|
||||
label(c, "R pad", 57, 32.5f, 2f);
|
||||
} else if (Settings.touchMode[0] == Settings.TOUCH_OFF) {
|
||||
label(c, "touchpad off", 50, 32.5f, 2f);
|
||||
} else {
|
||||
label(c, "whole pad", 50, 32.5f, 2f);
|
||||
}
|
||||
fingerOnRect(c, 36, 64, 12, 34, 0, 0xFFFFFFFF);
|
||||
fingerOnRect(c, 36, 64, 12, 34, 1, 0xFF4FC3F7);
|
||||
}
|
||||
|
||||
private void padRect(Canvas c, float l, float t, float r, float b, String lbl, int bit) {
|
||||
rect.set(l, t, r, b);
|
||||
fill.setColor(((mask >> bit) & 1) != 0 ? ORANGE : (((testedButtons >> bit) & 1) != 0 ? GREEN : 0xFF263238));
|
||||
c.drawRoundRect(rect, 2f, 2f, fill);
|
||||
stroke.setColor(LINE);
|
||||
c.drawRoundRect(rect, 2f, 2f, stroke);
|
||||
if (lbl != null) label(c, lbl, (l + r) / 2f, b - 1.5f, 2f);
|
||||
}
|
||||
|
||||
private void fingerOnRect(Canvas c, float l, float r, float t, float b, int fingerSlot, int color) {
|
||||
float[] f = frame;
|
||||
if (f[13 + 3 * fingerSlot] <= 0.5f) return;
|
||||
float nx = f[14 + 3 * fingerSlot] / 1919f, ny = f[15 + 3 * fingerSlot] / 1079f;
|
||||
if (Settings.touchInvX[0]) nx = 1f - nx;
|
||||
if (Settings.touchInvY[0]) ny = 1f - ny;
|
||||
fill.setColor(color);
|
||||
c.drawCircle(l + nx * (r - l), t + ny * (b - t), 1.8f, fill);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.content.Context;
|
||||
import android.hardware.usb.UsbConstants;
|
||||
import android.hardware.usb.UsbDevice;
|
||||
import android.hardware.usb.UsbDeviceConnection;
|
||||
import android.hardware.usb.UsbInterface;
|
||||
import android.hardware.usb.UsbManager;
|
||||
import android.os.Bundle;
|
||||
import android.util.Log;
|
||||
|
||||
/**
|
||||
* Steam Native Hook-up: everything Steam on Linux reads about a USB HID controller before it picks a driver --
|
||||
* vendor/product id, release number, name, serial, interface and the HID report descriptor -- taken from the
|
||||
* real USB device, so DroidDeck can describe a hidraw node that is indistinguishable from it.
|
||||
*/
|
||||
final class HookupIdentity {
|
||||
private static final String TAG = "SDL3Bridge";
|
||||
|
||||
// Generic Desktop / Gamepad collection with 64-byte vendor in/out reports. Used for controllers that have
|
||||
// no HID descriptor of their own (Xbox controllers speak GIP on a vendor-class interface).
|
||||
private static final byte[] VENDOR_GAMEPAD_DESCRIPTOR = bytes(
|
||||
0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x06, 0x00, 0xff, 0x09, 0x01, 0x15, 0x00, 0x26, 0xff, 0x00,
|
||||
0x75, 0x08, 0x95, 0x40, 0x81, 0x02, 0x09, 0x02, 0x95, 0x40, 0x91, 0x02, 0xc0);
|
||||
|
||||
private HookupIdentity() {}
|
||||
|
||||
/** Report descriptors read before the raw open, by SDL hid path. */
|
||||
private static final java.util.Map<String, byte[]> prefetched = new java.util.concurrent.ConcurrentHashMap<>();
|
||||
/** Report descriptors already read once, by "vid:pid:interface" -- reused when the same controller is handed
|
||||
* over again (hook-up off/on, replug), so the USB device is not asked again while a connection holds it. */
|
||||
private static final java.util.Map<String, byte[]> known = new java.util.concurrent.ConcurrentHashMap<>();
|
||||
/** How the last build() got its descriptor ("prefetched", "remembered", "read", "fallback"). */
|
||||
static volatile String lastSource = "";
|
||||
|
||||
private static String key(String path) {
|
||||
String[] p = path.split("/");
|
||||
int n = p.length;
|
||||
return n >= 3 ? p[n - 3] + ":" + p[n - 2] + ":" + p[n - 1] : path;
|
||||
}
|
||||
|
||||
static void prefetch(Context context, String path) {
|
||||
if (known.containsKey(key(path))) return; // nothing to read: it is remembered
|
||||
try {
|
||||
UsbManager um = (UsbManager) context.getSystemService(Context.USB_SERVICE);
|
||||
UsbDevice dev = um == null ? null : um.getDeviceList().get(deviceName(path));
|
||||
int index = ifaceIndex(path);
|
||||
if (dev == null || index < 0 || index >= dev.getInterfaceCount()) return;
|
||||
UsbInterface f = dev.getInterface(index);
|
||||
if (f.getInterfaceClass() != UsbConstants.USB_CLASS_HID) return;
|
||||
byte[] d = readWithTimeout(um, dev, f);
|
||||
if (d != null) { prefetched.put(path, d); known.put(key(path), d); }
|
||||
Log.i(TAG, "hookup: report descriptor of " + path + ": " + (d == null ? "unreadable" : d.length + " bytes"));
|
||||
} catch (RuntimeException e) {
|
||||
Log.w(TAG, "hookup: descriptor prefetch failed: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String deviceName(String path) {
|
||||
String n = path;
|
||||
for (int i = 0; i < 3 && n.lastIndexOf('/') > 0; i++) n = n.substring(0, n.lastIndexOf('/'));
|
||||
return n;
|
||||
}
|
||||
|
||||
private static int ifaceIndex(String path) {
|
||||
try { return Integer.parseInt(path.substring(path.lastIndexOf('/') + 1)); } catch (RuntimeException e) { return -1; }
|
||||
}
|
||||
|
||||
private static byte[] bytes(int... v) {
|
||||
byte[] b = new byte[v.length];
|
||||
for (int i = 0; i < v.length; i++) b[i] = (byte) v[i];
|
||||
return b;
|
||||
}
|
||||
|
||||
/** SDL's Android HID path is "<usb device name>/<vid hex>/<pid hex>/<interface index>". */
|
||||
static Bundle build(Context context, int slot, String path, int vid, int pid, int ifaceIndex) {
|
||||
Bundle b = new Bundle();
|
||||
b.putInt("slot", slot);
|
||||
b.putInt("vid", vid);
|
||||
b.putInt("pid", pid);
|
||||
b.putInt("bus", 3);
|
||||
String name = String.format("Controller %04x:%04x", vid, pid);
|
||||
String manufacturer = "", product = "", serial = "";
|
||||
int ifaceNumber = ifaceIndex, ifaceClass = UsbConstants.USB_CLASS_HID, ifaceSub = 0, ifaceProto = 0, version = 0x0100;
|
||||
byte[] descriptor = null;
|
||||
try {
|
||||
UsbManager um = (UsbManager) context.getSystemService(Context.USB_SERVICE);
|
||||
UsbDevice dev = um == null ? null : um.getDeviceList().get(deviceName(path));
|
||||
if (dev != null) {
|
||||
if (ifaceIndex >= 0 && ifaceIndex < dev.getInterfaceCount()) {
|
||||
UsbInterface f = dev.getInterface(ifaceIndex);
|
||||
ifaceNumber = f.getId();
|
||||
ifaceClass = f.getInterfaceClass();
|
||||
ifaceSub = f.getInterfaceSubclass();
|
||||
ifaceProto = f.getInterfaceProtocol();
|
||||
}
|
||||
try { manufacturer = nz(dev.getManufacturerName()); } catch (SecurityException ignored) { }
|
||||
try { product = nz(dev.getProductName()); } catch (SecurityException ignored) { }
|
||||
try { serial = nz(dev.getSerialNumber()); } catch (SecurityException ignored) { }
|
||||
version = parseBcd(dev.getVersion());
|
||||
descriptor = prefetched.remove(path);
|
||||
if (descriptor != null) lastSource = "prefetched";
|
||||
if (descriptor == null && (descriptor = known.get(key(path))) != null) lastSource = "remembered";
|
||||
if (descriptor == null && ifaceClass == UsbConstants.USB_CLASS_HID && ifaceIndex >= 0 && ifaceIndex < dev.getInterfaceCount()) {
|
||||
descriptor = readWithTimeout(um, dev, dev.getInterface(ifaceIndex));
|
||||
if (descriptor != null) { known.put(key(path), descriptor); lastSource = "read"; }
|
||||
}
|
||||
String joined = (manufacturer.isEmpty() || product.startsWith(manufacturer)) ? product : manufacturer + " " + product;
|
||||
if (!joined.trim().isEmpty()) name = joined.trim();
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
Log.w(TAG, "hookup: identity of " + path + " incomplete: " + e);
|
||||
}
|
||||
if (descriptor == null || descriptor.length == 0) { descriptor = VENDOR_GAMEPAD_DESCRIPTOR; lastSource = "fallback"; }
|
||||
b.putInt("version", version);
|
||||
b.putInt("iface", ifaceNumber);
|
||||
b.putInt("ifclass", ifaceClass);
|
||||
b.putInt("ifsub", ifaceSub);
|
||||
b.putInt("ifproto", ifaceProto);
|
||||
b.putString("name", name);
|
||||
b.putString("manufacturer", manufacturer);
|
||||
b.putString("product", product.isEmpty() ? name : product);
|
||||
b.putString("serial", serial);
|
||||
b.putByteArray("desc", descriptor);
|
||||
Log.i(TAG, String.format("hookup: slot %d = %04x:%04x \"%s\" interface %d class %d, descriptor %d bytes",
|
||||
slot, vid, pid, name, ifaceNumber, ifaceClass, descriptor.length));
|
||||
return b;
|
||||
}
|
||||
|
||||
private static String nz(String s) { return s == null ? "" : s.trim(); }
|
||||
|
||||
/** "1.00" / "2.24" -> bcdDevice. */
|
||||
private static int parseBcd(String v) {
|
||||
try {
|
||||
if (v == null) return 0x0100;
|
||||
String[] p = v.split("\\.");
|
||||
int major = Integer.parseInt(p[0], 16), minor = p.length > 1 ? Integer.parseInt(p[1], 16) : 0;
|
||||
return ((major & 0xff) << 8) | (minor & 0xff);
|
||||
} catch (RuntimeException e) {
|
||||
return 0x0100;
|
||||
}
|
||||
}
|
||||
|
||||
/** [readReportDescriptor] on its own thread, given up after 1.5 s: a USB request that never comes back must
|
||||
* not freeze the SDL thread (that would stop every controller until the app is restarted). */
|
||||
private static byte[] readWithTimeout(UsbManager um, UsbDevice dev, UsbInterface iface) {
|
||||
final byte[][] out = new byte[1][];
|
||||
Thread t = new Thread(() -> out[0] = readReportDescriptor(um, dev, iface), "hookup-descriptor");
|
||||
t.setDaemon(true);
|
||||
t.start();
|
||||
try { t.join(1500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
|
||||
if (t.isAlive()) {
|
||||
Log.w(TAG, "hookup: report descriptor read timed out");
|
||||
return null;
|
||||
}
|
||||
return out[0];
|
||||
}
|
||||
|
||||
/** GET_DESCRIPTOR(HID report) on the interface, over a second connection. */
|
||||
private static byte[] readReportDescriptor(UsbManager um, UsbDevice dev, UsbInterface iface) {
|
||||
UsbDeviceConnection c = null;
|
||||
try {
|
||||
c = um.openDevice(dev);
|
||||
if (c == null) return null;
|
||||
byte[] buf = new byte[4096];
|
||||
int ifaceNumber = iface.getId();
|
||||
// Interface-recipient request (the standard one). If another connection holds the interface,
|
||||
// Android refuses it; claim it briefly (nobody holds it right before the raw open), and as a last
|
||||
// resort ask with device recipient, which most controllers answer the same way.
|
||||
int n = c.controlTransfer(0x81, 0x06, 0x2200, ifaceNumber, buf, buf.length, 500);
|
||||
if (n <= 0 && c.claimInterface(iface, false)) {
|
||||
n = c.controlTransfer(0x81, 0x06, 0x2200, ifaceNumber, buf, buf.length, 500);
|
||||
c.releaseInterface(iface);
|
||||
}
|
||||
if (n <= 0) n = c.controlTransfer(0x80, 0x06, 0x2200, ifaceNumber, buf, buf.length, 500);
|
||||
if (n <= 0) return null;
|
||||
byte[] out = new byte[n];
|
||||
System.arraycopy(buf, 0, out, 0, n);
|
||||
return out;
|
||||
} catch (RuntimeException e) {
|
||||
return null;
|
||||
} finally {
|
||||
if (c != null) c.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
/**
|
||||
* Where this bridge runs: as its own app (SDL3Bridge, package com.example.dsedge), or built into SDL3DroidDeck --
|
||||
* the same code, in that app's ":sdl3" process. Built in, its settings are kept under their own names next to
|
||||
* DroidDeck's, and it updates together with SDL3DroidDeck (no update check of its own).
|
||||
*/
|
||||
final class Host {
|
||||
static final String OWN_PACKAGE = "com.example.dsedge";
|
||||
|
||||
private Host() {}
|
||||
|
||||
static boolean embedded(Context c) {
|
||||
return c != null && !OWN_PACKAGE.equals(c.getPackageName());
|
||||
}
|
||||
|
||||
/** A preferences file name of the bridge: unchanged as its own app, prefixed when built into another app. */
|
||||
static String prefs(Context c, String name) {
|
||||
return embedded(c) ? "sdl3bridge_" + name : name;
|
||||
}
|
||||
|
||||
/** The app's name as Android shows it ("SDL3DroidDeck" when built in). */
|
||||
static String appName(Context c) {
|
||||
try {
|
||||
CharSequence label = c.getPackageManager().getApplicationLabel(c.getApplicationInfo());
|
||||
return label != null ? label.toString() : c.getPackageName();
|
||||
} catch (RuntimeException e) {
|
||||
return c.getPackageName();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/** Glue between the native SDL3 loop (libmain.so) and the Java service. */
|
||||
public final class NativeBridge {
|
||||
public interface Listener {
|
||||
void onFrame(float[] f, int slot);
|
||||
void onStatus(String s);
|
||||
/** The controller in this slot (0..3) was unplugged. */
|
||||
default void onPadGone(int slot) { }
|
||||
/** Capabilities of the controller in this slot: which buttons/axes exist, touchpad count, and kind. */
|
||||
default void onPadCaps(int slot, int present, int axes, int touchpads, String kind) { }
|
||||
/** Steam Controller (2026) raw passthrough: one input report (id + payload without the id byte). */
|
||||
default void onTritonState(int reportId, byte[] payload) { }
|
||||
/** The passed-through Steam Controller (2026) appeared / went away. */
|
||||
default void onTritonConnected(boolean connected, String what) { }
|
||||
/** Answer to a feature read DroidDeck forwarded (null = the controller did not answer). */
|
||||
default void onTritonFeature(long request, byte[] report) { }
|
||||
/** Steam Native Hook-up: a controller was handed to Steam in [slot]; identity = HookupIdentity bundle. */
|
||||
default void onHookupAdded(int slot, android.os.Bundle identity) { }
|
||||
default void onHookupInput(int slot, byte[] report) { }
|
||||
default void onHookupRemoved(int slot) { }
|
||||
default void onHookupReply(int slot, long request, byte[] report) { }
|
||||
/** A line from the bridge's hook-up / passthrough code, for DroidDeck's session log. */
|
||||
default void onBridgeLog(String line) { }
|
||||
}
|
||||
|
||||
/** Layout of the float[] frame sent from native code. */
|
||||
public static final int FRAME_LEN = 22;
|
||||
// 0 mask | 1..4 lx ly rx ry (0..255) | 5,6 l2 r2 (0..255) | 7..9 gyro rad/s | 10..12 accel m/s^2
|
||||
// 13..15 finger0 (down,x,y) | 16..18 finger1 | 19 battery % (-1 unknown) | 20 SDL power state | 21 extra-button mask (MISC2..6)
|
||||
|
||||
static final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<>();
|
||||
static volatile String lastStatus = "Starting...";
|
||||
|
||||
static final int MAX_PADS = 4;
|
||||
/** USB ids and names of the controller in each slot, so DroidDeck can ignore the Android duplicate of it. */
|
||||
static final int[] vids = new int[MAX_PADS], pids = new int[MAX_PADS];
|
||||
static final String[] names = new String[MAX_PADS];
|
||||
|
||||
private NativeBridge() {}
|
||||
|
||||
/** Called from the native SDL thread. */
|
||||
static void onFrame(float[] f, int slot) {
|
||||
for (Listener l : listeners) l.onFrame(f, slot);
|
||||
}
|
||||
|
||||
/** Called from the native SDL thread when a controller is opened in a slot. */
|
||||
static void onPadInfo(int slot, int vid, int pid, String name) {
|
||||
if (slot < 0 || slot >= MAX_PADS) return;
|
||||
vids[slot] = vid;
|
||||
pids[slot] = pid;
|
||||
names[slot] = name;
|
||||
}
|
||||
|
||||
/** Capabilities of each slot's controller (present-button mask, axis flags, touchpad count, kind). */
|
||||
static final int[] present = new int[MAX_PADS];
|
||||
static final int[] axesMask = new int[MAX_PADS];
|
||||
static final int[] touchpadCount = new int[MAX_PADS];
|
||||
static final String[] kind = new String[MAX_PADS];
|
||||
|
||||
/** Called from the native SDL thread when a controller is opened in a slot. */
|
||||
static void onPadCaps(int slot, int p, int a, int tp, String k) {
|
||||
if (slot < 0 || slot >= MAX_PADS) return;
|
||||
present[slot] = p;
|
||||
axesMask[slot] = a;
|
||||
touchpadCount[slot] = tp;
|
||||
kind[slot] = k;
|
||||
for (Listener l : listeners) l.onPadCaps(slot, p, a, tp, k);
|
||||
}
|
||||
|
||||
/** Called from the native SDL thread when a slot's controller goes away. */
|
||||
static void onPadGone(int slot) {
|
||||
if (slot < 0 || slot >= MAX_PADS) return;
|
||||
vids[slot] = 0;
|
||||
pids[slot] = 0;
|
||||
names[slot] = null;
|
||||
for (Listener l : listeners) l.onPadGone(slot);
|
||||
}
|
||||
|
||||
// ---------- Steam Controller (2026) raw passthrough (native/triton.h) ----------
|
||||
static volatile boolean tritonConnected;
|
||||
static volatile String tritonWhat = "";
|
||||
|
||||
/** Called from the native SDL thread for every state report. */
|
||||
static void onTritonState(int reportId, byte[] payload) {
|
||||
for (Listener l : listeners) l.onTritonState(reportId, payload);
|
||||
}
|
||||
|
||||
/** Called from the native SDL thread. */
|
||||
static void onTritonConnected(boolean connected, String what) {
|
||||
tritonConnected = connected;
|
||||
tritonWhat = what == null ? "" : what;
|
||||
for (Listener l : listeners) l.onTritonConnected(connected, tritonWhat);
|
||||
}
|
||||
|
||||
/** Called from the native SDL thread. */
|
||||
static void onTritonFeature(long request, byte[] report) {
|
||||
for (Listener l : listeners) l.onTritonFeature(request, report);
|
||||
}
|
||||
|
||||
/** An output report (feature = false) or a feature-report write (feature = true) from Steam, report id first. */
|
||||
static void tritonOutput(byte[] report, boolean feature) {
|
||||
try { nativeTritonOutput(report, feature); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static void tritonGetFeature(long request, int reportId) {
|
||||
try { nativeTritonGetFeature(request, reportId); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
/** Game rumble for the passed-through controller, 0..65535 per motor. */
|
||||
static void tritonRumble(int left, int right) {
|
||||
try { nativeTritonRumble(left, right); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static native void nativeTritonOutput(byte[] report, boolean feature);
|
||||
static native void nativeTritonGetFeature(long request, int reportId);
|
||||
static native void nativeTritonRumble(int left, int right);
|
||||
|
||||
// ---------- Steam Native Hook-up (native/hookup.h) ----------
|
||||
static volatile android.content.Context appContext;
|
||||
static final android.os.Bundle[] hookupIdentity = new android.os.Bundle[MAX_PADS];
|
||||
/** Controllers opened raw by native code: {path, vid, pid, interface}; kept until they are released. */
|
||||
static final Object[][] hookupPending = new Object[MAX_PADS][];
|
||||
|
||||
/** A controller that is open but was never described (that failed): try again, off the SDL thread. */
|
||||
static void retryUndescribed() {
|
||||
for (int i = 0; i < MAX_PADS; i++) {
|
||||
Object[] p = hookupPending[i];
|
||||
if (p == null || hookupIdentity[i] != null) continue;
|
||||
final int slot = i;
|
||||
new Thread(() -> {
|
||||
if (hookupPending[slot] == p && hookupIdentity[slot] == null)
|
||||
onHookupAdded(slot, (String) p[0], (Integer) p[1], (Integer) p[2], (Integer) p[3]);
|
||||
}, "hookup-retry").start();
|
||||
}
|
||||
}
|
||||
|
||||
static void onHookupAdded(int slot, String path, int vid, int pid, int ifaceIndex) {
|
||||
if (slot < 0 || slot >= MAX_PADS) return;
|
||||
hookupPending[slot] = new Object[] { path, vid, pid, ifaceIndex };
|
||||
android.content.Context c = appContext;
|
||||
if (c == null) {
|
||||
onBridgeLog("hookup: slot " + slot + " cannot be described (the app is not fully started); it is retried");
|
||||
return;
|
||||
}
|
||||
long t0 = android.os.SystemClock.uptimeMillis();
|
||||
android.os.Bundle id;
|
||||
try {
|
||||
id = HookupIdentity.build(c, slot, path, vid, pid, ifaceIndex);
|
||||
} catch (Throwable e) {
|
||||
onBridgeLog("hookup: slot " + slot + " could not be described: " + e);
|
||||
return;
|
||||
}
|
||||
hookupIdentity[slot] = id;
|
||||
byte[] d = id.getByteArray("desc");
|
||||
onBridgeLog(String.format(java.util.Locale.US, "hookup: slot %d described in %d ms (descriptor %d bytes, %s); sent to %d DroidDeck connection(s)",
|
||||
slot, android.os.SystemClock.uptimeMillis() - t0, d == null ? 0 : d.length, HookupIdentity.lastSource, clientCount()));
|
||||
for (Listener l : listeners) {
|
||||
try { l.onHookupAdded(slot, id); } catch (RuntimeException e) { android.util.Log.w("SDL3Bridge", "hookup: listener failed: " + e); }
|
||||
}
|
||||
}
|
||||
|
||||
/** DroidDeck connections, for the log (set by BridgeService). */
|
||||
static volatile java.util.function.IntSupplier clients;
|
||||
private static int clientCount() {
|
||||
java.util.function.IntSupplier s = clients;
|
||||
return s == null ? -1 : s.getAsInt();
|
||||
}
|
||||
|
||||
/** Recent bridge log lines (newest last), replayed to DroidDeck when it connects. */
|
||||
static final java.util.ArrayDeque<String> bridgeLog = new java.util.ArrayDeque<>();
|
||||
|
||||
/** Called from the native SDL thread. */
|
||||
static void onBridgeLog(String line) {
|
||||
String stamped = new java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.US).format(new java.util.Date()) + " " + line;
|
||||
synchronized (bridgeLog) {
|
||||
bridgeLog.addLast(stamped);
|
||||
while (bridgeLog.size() > 200) bridgeLog.removeFirst();
|
||||
}
|
||||
for (Listener l : listeners) l.onBridgeLog(stamped);
|
||||
}
|
||||
|
||||
/** Called from the native SDL thread just before a controller is opened raw. */
|
||||
static void prefetchHookupDescriptor(String path) {
|
||||
android.content.Context c = appContext;
|
||||
if (c != null) HookupIdentity.prefetch(c, path);
|
||||
}
|
||||
|
||||
static void onHookupInput(int slot, byte[] report) {
|
||||
for (Listener l : listeners) l.onHookupInput(slot, report);
|
||||
}
|
||||
|
||||
static void onHookupRemoved(int slot) {
|
||||
if (slot < 0 || slot >= MAX_PADS) return;
|
||||
hookupPending[slot] = null;
|
||||
hookupIdentity[slot] = null;
|
||||
for (Listener l : listeners) l.onHookupRemoved(slot);
|
||||
}
|
||||
|
||||
static void onHookupReply(int slot, long request, byte[] report) {
|
||||
for (Listener l : listeners) l.onHookupReply(slot, request, report);
|
||||
}
|
||||
|
||||
static void applyHookup() {
|
||||
try { nativeSetHookup(hookupMode()); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
// ---- DroidDeck's desktop: Steam Native Hook-up waits for Steam ----
|
||||
// On DroidDeck's desktop Steam is one program among others and may not be running. DroidDeck says so with each
|
||||
// watchdog sync (every 1.5 s); while it does, hook-up waits: controllers stay ordinary gamepads every program
|
||||
// can use, and are handed to Steam once its client runs. Lapses by itself if DroidDeck stops saying it.
|
||||
private static volatile long steamAwayUntilMs;
|
||||
private static volatile int hookupApplied = -1;
|
||||
|
||||
/** 0 off, 1 on, 2 on but waiting for Steam (DroidDeck's desktop without Steam running). */
|
||||
static int hookupMode() {
|
||||
if (!Settings.isHookup()) return 0;
|
||||
return android.os.SystemClock.uptimeMillis() < steamAwayUntilMs ? 2 : 1;
|
||||
}
|
||||
|
||||
static boolean hookupWaitsForSteam() { return hookupMode() == 2; }
|
||||
|
||||
/** From DroidDeck's sync: is Steam away (its desktop without the Steam client running)? */
|
||||
static void setSteamAway(boolean away) {
|
||||
steamAwayUntilMs = away ? android.os.SystemClock.uptimeMillis() + 10000 : 0;
|
||||
recheckHookup();
|
||||
}
|
||||
|
||||
/** Applies hook-up again if waiting for Steam started or ended (also when the wait lapsed). */
|
||||
static void recheckHookup() {
|
||||
int mode = hookupMode();
|
||||
if (mode == hookupApplied) return;
|
||||
int was = hookupApplied;
|
||||
hookupApplied = mode;
|
||||
if (mode == 2) onBridgeLog("hookup: DroidDeck's desktop has no Steam running: controllers stay ordinary gamepads until it starts");
|
||||
else if (was == 2 && mode == 1) onBridgeLog("hookup: Steam runs on DroidDeck's desktop: controllers are handed to Steam");
|
||||
applyHookup();
|
||||
}
|
||||
|
||||
static void hookupOutput(int slot, int kind, byte[] report) {
|
||||
try { nativeHookupOutput(slot, kind, report); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static void hookupGet(int slot, long request, int reportId, boolean input, int length) {
|
||||
try { nativeHookupGet(slot, request, reportId, input, length); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static native void nativeSetHookup(int on);
|
||||
static native int nativeHookupMapShm(int fd);
|
||||
static native long nativeHookupShmInode();
|
||||
|
||||
/** DroidDeck's shared hook-up file (fast path: reports written straight into it). Takes ownership of pfd. */
|
||||
static void hookupMapShm(android.os.ParcelFileDescriptor pfd) {
|
||||
if (pfd == null) return;
|
||||
try { nativeHookupMapShm(pfd.detachFd()); }
|
||||
catch (UnsatisfiedLinkError e) { try { pfd.close(); } catch (java.io.IOException ignored) { } }
|
||||
}
|
||||
|
||||
/** Inode of the mapped (still live) shared file, 0 if none. */
|
||||
static long hookupShmInode() {
|
||||
try { return nativeHookupShmInode(); } catch (UnsatisfiedLinkError e) { return 0; }
|
||||
}
|
||||
static native void nativeHookupOutput(int slot, int kind, byte[] report);
|
||||
static native void nativeHookupGet(int slot, long request, int reportId, boolean input, int length);
|
||||
|
||||
/** Called from the native SDL thread. */
|
||||
static void onStatus(String s) {
|
||||
SdlEngine.onNativeStatus();
|
||||
lastStatus = s;
|
||||
for (Listener l : listeners) l.onStatus(s);
|
||||
}
|
||||
|
||||
/** Rumble for any player slot (0..3). */
|
||||
static void setRumble(int slot, int strong, int weak) {
|
||||
if (slot < 0 || slot >= MAX_PADS) return;
|
||||
try { nativeSetRumble(slot, strong, weak); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static native void nativeSetRumble(int slot, int rumbleStrong, int rumbleWeak);
|
||||
|
||||
/** Pushes each player's lightbar (scaled by brightness) and player LED to its controller. */
|
||||
static void applyOutput() {
|
||||
try {
|
||||
for (int p = 0; p < MAX_PADS; p++) {
|
||||
int b = Settings.brightness[p];
|
||||
nativeSetLed(p, Settings.lightR[p] * b / 100, Settings.lightG[p] * b / 100, Settings.lightB[p] * b / 100);
|
||||
nativeSetPlayerLed(p, Settings.playerLed[p] - 1); // -1 = player LEDs off
|
||||
}
|
||||
} catch (UnsatisfiedLinkError e) {
|
||||
// The bridge screen has not been opened yet, so the native library is not loaded.
|
||||
}
|
||||
}
|
||||
|
||||
/** Apply just one player's light (on a settings change). */
|
||||
static void applyOutput(int p) {
|
||||
if (p < 0 || p >= MAX_PADS) return;
|
||||
try {
|
||||
int b = Settings.brightness[p];
|
||||
nativeSetLed(p, Settings.lightR[p] * b / 100, Settings.lightG[p] * b / 100, Settings.lightB[p] * b / 100);
|
||||
nativeSetPlayerLed(p, Settings.playerLed[p] - 1);
|
||||
} catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
/** Forced mode: ignore Android's basic input and only use SDL's own USB driver. */
|
||||
static void applyForce() {
|
||||
try { nativeSetForce(Settings.forceUsb ? 1 : 0); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static void rescan() {
|
||||
try { nativeRescan(); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static native void nativeSetForce(int on);
|
||||
|
||||
static native void nativeRescan();
|
||||
|
||||
/** Hard on/off for the SDL3 driver: on = forced SDL3 USB, off = release the controller to Android. */
|
||||
static void applyDriver() {
|
||||
try {
|
||||
nativeSetDriver(Settings.driverEnabled ? 1 : 0);
|
||||
nativeSetHookup(hookupMode());
|
||||
if (Settings.driverEnabled) nativeSetForce(Settings.forceUsb ? 1 : 0);
|
||||
} catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static native void nativeSetDriver(int on);
|
||||
|
||||
/** Controller poll rate (loop period in ms). */
|
||||
static void applyRate() {
|
||||
try { nativeSetPollMs(Settings.pollMs); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static native void nativeSetPollMs(int ms);
|
||||
|
||||
/** Per-slot lightbar rgb 0..255. */
|
||||
static native void nativeSetLed(int slot, int r, int g, int b);
|
||||
|
||||
/** Per-slot player LEDs: -1 = off, 0..3 = player 1..4. */
|
||||
static native void nativeSetPlayerLed(int slot, int index);
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
import android.util.Log;
|
||||
|
||||
import org.libsdl.app.HIDDeviceManager;
|
||||
import org.libsdl.app.SDL;
|
||||
import org.libsdl.app.SDLActivity;
|
||||
|
||||
/**
|
||||
* Where SDL3 runs.
|
||||
*
|
||||
* Normally headless, inside the bridge's background service -- no screen has to open for the bridge to work. It
|
||||
* does what SDL's own SDLActivity does at start-up, minus the window: load the libraries, set up SDL's Java side,
|
||||
* take USB/HID access (HIDDeviceManager), then run SDL_main (main.c) on its own thread. The bridge only uses SDL's
|
||||
* gamepad / joystick / hidapi parts, which need no window.
|
||||
*
|
||||
* SDL's Java side does expect "the app's screen" as its context (SDL.getContext()): SDL3 reads the app's files
|
||||
* and assets through it while it starts (gamepad mappings), and crashes the whole app without one. Headless there
|
||||
* is no screen, so AppContext stands in for it -- an Activity object that is never started or shown, whose calls
|
||||
* all go to the app. The mappings file is also handed to SDL3 directly, so it never needs the assets for it.
|
||||
*
|
||||
* Self-protecting: a marker is saved before every background start and cleared when SDL3's loop reports its first
|
||||
* status. If SDL3 stays silent for 10 s (the process is then restarted), or the app died during the attempt, this
|
||||
* build uses the fallback instead: SDL3 runs inside the bridge's own screen, started when you open SDL3Bridge
|
||||
* (nothing opens by itself). Every step, and the previous run's crash report if there was one, is sent to
|
||||
* DroidDeck's session log ("sdl3bridge: engine: ...").
|
||||
*/
|
||||
final class SdlEngine {
|
||||
private static final String TAG = "SDL3Bridge";
|
||||
private static final long CONFIRM_MS = 10_000;
|
||||
private static volatile boolean started, confirmed, fallback, failed;
|
||||
private static volatile HIDDeviceManager hid;
|
||||
private static long hostStartMs;
|
||||
/** Why SDL3 is not running (shown in the status, the notification and DroidDeck's tab), or null. */
|
||||
static volatile String error;
|
||||
/** How SDL3 runs now, for the status / DroidDeck's tab. */
|
||||
static volatile String mode = "not started";
|
||||
private static String fallbackWhy = "";
|
||||
|
||||
private SdlEngine() {}
|
||||
|
||||
static boolean isRunning() { return started && (fallback ? SdlHostActivity.running : true); }
|
||||
|
||||
private static void log(String line) {
|
||||
Log.i(TAG, line);
|
||||
NativeBridge.onBridgeLog("engine: " + line);
|
||||
}
|
||||
|
||||
private static SharedPreferences prefs(Context c) { return c.getSharedPreferences(Host.prefs(c, "engine"), Context.MODE_PRIVATE); }
|
||||
|
||||
/** Which build this is: the version code, or -- built into SDL3DroidDeck, whose version code stays the same from
|
||||
* build to build -- when it was installed, so a new build tries the background again. */
|
||||
private static long version(Context c) {
|
||||
try {
|
||||
android.content.pm.PackageInfo pi = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
|
||||
if (Host.embedded(c)) return pi.lastUpdateTime;
|
||||
return android.os.Build.VERSION.SDK_INT >= 28 ? pi.getLongVersionCode() : pi.versionCode;
|
||||
} catch (Exception e) { return 0; }
|
||||
}
|
||||
|
||||
/** Stands in for "the app's screen" in SDL's Java side (see the class comment). Never started or shown. */
|
||||
static final class AppContext extends Activity {
|
||||
AppContext(Context base) { attachBaseContext(base); }
|
||||
}
|
||||
|
||||
private static Activity standIn(Context app) {
|
||||
try {
|
||||
Context base;
|
||||
// its own copy of the app's context, so nothing set on the stand-in reaches the app's real one
|
||||
try { base = app.createConfigurationContext(app.getResources().getConfiguration()); }
|
||||
catch (RuntimeException e) { base = app; }
|
||||
return new AppContext(base);
|
||||
} catch (Throwable e) {
|
||||
log("could not make SDL3's stand-in context (" + e + "); starting without one");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** SDL3's gamepad mappings file (empty unless you add mappings), as an absolute path; null if unavailable. */
|
||||
static String mappingFile(Context c) {
|
||||
try {
|
||||
java.io.File f = new java.io.File(c.getFilesDir(), "gamepad_map.txt");
|
||||
if (!f.exists() && !f.createNewFile()) return null;
|
||||
return f.getAbsolutePath();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Starts SDL once per process (safe to call again, from any thread). */
|
||||
static void start(Context context) {
|
||||
if (Looper.myLooper() != Looper.getMainLooper()) { // the stand-in context must be made on the main thread
|
||||
new Handler(Looper.getMainLooper()).post(() -> start(context));
|
||||
return;
|
||||
}
|
||||
startOnMain(context);
|
||||
}
|
||||
|
||||
private static synchronized void startOnMain(Context context) {
|
||||
final Context app = context.getApplicationContext();
|
||||
NativeBridge.appContext = app;
|
||||
Settings.init(app);
|
||||
if (started) {
|
||||
if (fallback && !SdlHostActivity.running && context instanceof Activity) startHost((Activity) context);
|
||||
return;
|
||||
}
|
||||
started = true;
|
||||
SharedPreferences p = prefs(app);
|
||||
long ver = version(app);
|
||||
String last = p.getString("state", "");
|
||||
boolean sameBuild = p.getLong("version", -1) == ver;
|
||||
if (sameBuild && (last.equals("starting") || last.startsWith("failed"))) {
|
||||
boolean crashed = last.equals("starting");
|
||||
fallbackWhy = crashed ? "the app stopped while SDL3 was starting in the background" : last.substring(last.indexOf(':') + 1).trim();
|
||||
if (crashed) p.edit().putString("state", "failed: " + fallbackWhy).commit();
|
||||
fallback = true;
|
||||
mode = "the SDL3Bridge screen (fallback)";
|
||||
error = "Open SDL3Bridge once to start SDL3 (it could not run in the background on this phone: " + fallbackWhy + ")";
|
||||
log("SDL3 can't run in the background service with this build (" + fallbackWhy + "). Fallback: SDL3 runs "
|
||||
+ "inside the SDL3Bridge screen -- open SDL3Bridge once (nothing opens by itself). A new build tries "
|
||||
+ "the background again.");
|
||||
if (crashed) forwardPreviousLog();
|
||||
if (context instanceof Activity) startHost((Activity) context);
|
||||
return;
|
||||
}
|
||||
p.edit().putString("state", "starting").putLong("version", ver).commit(); // commit: must survive a crash
|
||||
log("starting SDL3 in the background service (build " + ver + ")");
|
||||
try {
|
||||
System.loadLibrary("SDL3");
|
||||
System.loadLibrary("main");
|
||||
log("libraries loaded");
|
||||
SDL.setupJNI();
|
||||
SDL.initialize(); // (this also clears SDL's context)
|
||||
Activity ctx = standIn(app);
|
||||
if (ctx != null) SDL.setContext(ctx);
|
||||
log("SDL3's Java side ready" + (ctx != null ? " (stand-in context)" : " (no context)"));
|
||||
hid = HIDDeviceManager.acquire(app);
|
||||
hid.setFrozen(!Settings.driverEnabled);
|
||||
log("USB/HID access ready");
|
||||
} catch (Throwable e) {
|
||||
fail(app, "SDL3 could not start: " + e);
|
||||
restartForFallback("SDL3 could not start in the background service");
|
||||
return;
|
||||
}
|
||||
final String main = app.getApplicationInfo().nativeLibraryDir + "/libmain.so";
|
||||
final String map = mappingFile(app);
|
||||
final String[] args = map != null ? new String[] { map } : new String[0];
|
||||
Thread t = new Thread(() -> {
|
||||
try { android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_DISPLAY); } catch (RuntimeException ignored) { }
|
||||
try {
|
||||
SDLActivity.nativeInitMainThread();
|
||||
int rc = SDLActivity.nativeRunMain(main, "SDL_main", args);
|
||||
SDLActivity.nativeCleanupMainThread();
|
||||
fail(app, "SDL3's loop ended (" + rc + ")");
|
||||
} catch (Throwable e) {
|
||||
fail(app, "SDL3 stopped: " + e);
|
||||
}
|
||||
restartForFallback("SDL3's loop is not running");
|
||||
}, "SDLThread");
|
||||
error = null;
|
||||
mode = "background service";
|
||||
t.start();
|
||||
log("SDL3 thread started; waiting for its first status");
|
||||
// Settings the native loop reads (driver, hook-up, rate, lights), as the bridge screen used to apply.
|
||||
NativeBridge.applyDriver();
|
||||
NativeBridge.applyRate();
|
||||
NativeBridge.applyOutput();
|
||||
new Handler(Looper.getMainLooper()).postDelayed(() -> {
|
||||
if (confirmed || fallback || failed) return; // working, or already failed (and restarting)
|
||||
fail(app, "SDL3 did not answer within " + (CONFIRM_MS / 1000) + " s in the background service");
|
||||
restartForFallback("SDL3 did not answer");
|
||||
}, CONFIRM_MS);
|
||||
}
|
||||
|
||||
/** SDL3's loop reported a status: it runs. */
|
||||
static void onNativeStatus() {
|
||||
if (!started) return;
|
||||
if (fallback) {
|
||||
if (error != null && SdlHostActivity.running) {
|
||||
error = null;
|
||||
log("SDL3 is running in the SDL3Bridge screen (fallback); you can leave the screen, it keeps running");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (confirmed) return;
|
||||
confirmed = true;
|
||||
Context c = NativeBridge.appContext;
|
||||
if (c != null) prefs(c).edit().putString("state", "ok").apply();
|
||||
log("SDL3 is running in the background service");
|
||||
}
|
||||
|
||||
/**
|
||||
* The fallback screen was closed for good (its task was swiped away): SDL3 can't be restarted cleanly in the
|
||||
* same process, so the process restarts (DroidDeck's connection brings the service back) and the bridge waits
|
||||
* to be opened again.
|
||||
*/
|
||||
static void onHostGone() {
|
||||
if (!fallback) return;
|
||||
error = "Open SDL3Bridge to start SDL3 again (fallback: " + fallbackWhy + ")";
|
||||
log("the SDL3Bridge screen that ran SDL3 was closed; restarting SDL3Bridge -- open it again to start SDL3");
|
||||
new Handler(Looper.getMainLooper()).postDelayed(
|
||||
() -> android.os.Process.killProcess(android.os.Process.myPid()), 1500);
|
||||
}
|
||||
|
||||
/** The process restarts (DroidDeck's connection brings the service back) and the next start uses the fallback. */
|
||||
private static void restartForFallback(String why) {
|
||||
log(why + "; restarting SDL3Bridge in 2 s so the fallback takes over");
|
||||
new Handler(Looper.getMainLooper()).postDelayed(
|
||||
() -> android.os.Process.killProcess(android.os.Process.myPid()), 2000); // lets the log reach DroidDeck
|
||||
}
|
||||
|
||||
private static void fail(Context app, String why) {
|
||||
failed = true;
|
||||
error = why;
|
||||
Log.e(TAG, why);
|
||||
NativeBridge.onBridgeLog("engine: " + why);
|
||||
prefs(app).edit().putString("state", "failed: " + why).commit();
|
||||
}
|
||||
|
||||
/** Fallback only, and only from the bridge's own screen while you look at it: SDL3's host screen on top of it. */
|
||||
private static void startHost(Activity from) {
|
||||
long now = SystemClock.uptimeMillis();
|
||||
if (hostStartMs != 0 && now - hostStartMs < 5000) return; // never in a loop
|
||||
hostStartMs = now;
|
||||
try {
|
||||
from.startActivity(new Intent(from, SdlHostActivity.class).addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
|
||||
log("starting SDL3 in the SDL3Bridge screen (fallback)");
|
||||
} catch (RuntimeException e) {
|
||||
log("could not start SDL3 in the SDL3Bridge screen: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
/** The previous run's own log lines about SDL / the bridge / a crash, into DroidDeck's session log. */
|
||||
private static void forwardPreviousLog() {
|
||||
new Thread(() -> {
|
||||
java.util.ArrayDeque<String> keep = new java.util.ArrayDeque<>();
|
||||
try {
|
||||
java.lang.Process p = Runtime.getRuntime().exec(new String[] { "logcat", "-d", "-v", "time", "-t", "3000" });
|
||||
try (java.io.BufferedReader r = new java.io.BufferedReader(new java.io.InputStreamReader(p.getInputStream()))) {
|
||||
String line;
|
||||
while ((line = r.readLine()) != null) {
|
||||
if (line.contains("AndroidRuntime") || line.contains(" F/") || line.contains("/SDL")
|
||||
|| line.contains("SDL3Bridge") || line.contains("libc") || line.contains("DEBUG")
|
||||
|| line.contains("/hidapi") || line.contains("JNI DETECTED")) {
|
||||
keep.addLast(line);
|
||||
while (keep.size() > 80) keep.removeFirst();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
keep.addLast("(could not read the log: " + e + ")");
|
||||
}
|
||||
NativeBridge.onBridgeLog("engine: ---- the bridge's own log (last " + keep.size() + " relevant lines) ----");
|
||||
for (String l : keep) NativeBridge.onBridgeLog("engine: | " + l);
|
||||
}, "engine-log").start();
|
||||
}
|
||||
|
||||
/** Driver off = release the USB interface so Android can use the controller; on = claim it again. */
|
||||
static void setHidFrozen(boolean frozen) {
|
||||
HIDDeviceManager h = hid;
|
||||
if (h != null) h.setFrozen(frozen);
|
||||
else SdlHostActivity.setHidFrozen(frozen);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import org.libsdl.app.SDLActivity;
|
||||
|
||||
/**
|
||||
* Fallback host for SDL3, used only when SDL3 could not run in the background service with this build
|
||||
* (SdlEngine decides, and says why). SDL's own screen class starts SDL3 the classic way; it is opened only from the
|
||||
* bridge's screen while you look at it, never by itself.
|
||||
*
|
||||
* It stays out of sight: its window is transparent and SDL's drawing surface is shrunk to one pixel (the bridge
|
||||
* draws nothing). SDL3 starts once this screen is in front, then the bridge's screen is brought back on top of it
|
||||
* in the same task; SDL3 keeps running behind it, and when you leave SDL3Bridge (Home, Back, switching apps).
|
||||
*/
|
||||
public class SdlHostActivity extends SDLActivity {
|
||||
static volatile boolean running;
|
||||
private final Handler ui = new Handler(Looper.getMainLooper());
|
||||
private int waits;
|
||||
|
||||
@Override protected String[] getLibraries() {
|
||||
return new String[] { "SDL3", "main" };
|
||||
}
|
||||
|
||||
@Override protected String[] getArguments() {
|
||||
String map = SdlEngine.mappingFile(this);
|
||||
return map != null ? new String[] { map } : new String[0];
|
||||
}
|
||||
|
||||
@Override protected void onCreate(Bundle state) {
|
||||
running = true;
|
||||
NativeBridge.appContext = getApplicationContext();
|
||||
Settings.init(this);
|
||||
super.onCreate(state);
|
||||
if (mSurface != null) { // SDL's drawing surface: the bridge draws nothing, keep it out of sight
|
||||
ViewGroup.LayoutParams lp = mSurface.getLayoutParams();
|
||||
if (lp != null) {
|
||||
lp.width = 1;
|
||||
lp.height = 1;
|
||||
mSurface.setLayoutParams(lp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override protected void onResume() {
|
||||
super.onResume();
|
||||
keepControllerClaimed();
|
||||
waits = 0;
|
||||
ui.removeCallbacks(handBack);
|
||||
ui.post(handBack);
|
||||
}
|
||||
|
||||
/** As soon as SDL3's thread runs: the bridge's screen back on top (or, if it is gone, out of the way). */
|
||||
private final Runnable handBack = new Runnable() {
|
||||
@Override public void run() {
|
||||
if (isFinishing()) return;
|
||||
if (mSDLThread == null && ++waits < 60) { // SDL starts once its surface is ready (~100 ms)
|
||||
ui.postDelayed(this, 50);
|
||||
return;
|
||||
}
|
||||
if (BridgeActivity.running) {
|
||||
startActivity(new Intent(SdlHostActivity.this, BridgeActivity.class)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NO_ANIMATION));
|
||||
} else {
|
||||
moveTaskToBack(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@Override public void onBackPressed() {
|
||||
moveTaskToBack(true); // closing this screen would stop SDL3
|
||||
}
|
||||
|
||||
@Override protected void onPause() {
|
||||
super.onPause();
|
||||
ui.removeCallbacks(handBack);
|
||||
keepControllerClaimed(); // SDL releases the USB controller on pause; keep it while DroidDeck is in front
|
||||
}
|
||||
|
||||
@Override public void onWindowFocusChanged(boolean hasFocus) {
|
||||
super.onWindowFocusChanged(hasFocus);
|
||||
keepControllerClaimed();
|
||||
}
|
||||
|
||||
@Override protected void onDestroy() {
|
||||
ui.removeCallbacks(handBack);
|
||||
running = false;
|
||||
boolean forGood = !isChangingConfigurations();
|
||||
super.onDestroy();
|
||||
if (forGood) SdlEngine.onHostGone();
|
||||
}
|
||||
|
||||
private static void keepControllerClaimed() {
|
||||
if (mHIDDeviceManager != null) mHIDDeviceManager.setFrozen(!Settings.driverEnabled);
|
||||
}
|
||||
|
||||
static void setHidFrozen(boolean frozen) {
|
||||
if (mHIDDeviceManager != null) mHIDDeviceManager.setFrozen(frozen);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
|
||||
/**
|
||||
* User settings, shared by the screen and the background service (same process).
|
||||
* Gyro / touchpad / back-button remap / lightbar are per player (0..3); the rest are global.
|
||||
*/
|
||||
final class Settings {
|
||||
static final int PLAYERS = 4;
|
||||
|
||||
static final int TOUCH_SPLIT = 0, TOUCH_SINGLE = 1, TOUCH_OFF = 2;
|
||||
static final String[] TOUCH_NAMES = {
|
||||
"Split (decoupled): left half = left trackpad, right half = right trackpad",
|
||||
"Single: whole touchpad = right trackpad",
|
||||
"Off"
|
||||
};
|
||||
|
||||
/** Remap targets: 4 Deck grips + the two trackpads' touch / click. */
|
||||
static final String[] REMAP_TARGETS = {
|
||||
"L4", "R4", "L5", "R5",
|
||||
"Left trackpad click", "Right trackpad click",
|
||||
"Left trackpad touch", "Right trackpad touch"
|
||||
};
|
||||
static final int REMAP_COUNT = 8;
|
||||
static final int[] TARGET_BITS = { 19, 20, 21, 22 }; // grip targets (first 4) -> mask bits
|
||||
|
||||
/** Any controller button can be a source. sel: -1 none, 0 = main mask, 1 = extra mask (MISC2..6). */
|
||||
static final String[] SRC_NAMES = {
|
||||
"None",
|
||||
"A / Cross", "B / Circle", "X / Square", "Y / Triangle",
|
||||
"L1", "R1", "L2", "R2",
|
||||
"Create / Back / Share", "Options / Start / Menu", "L3", "R3",
|
||||
"Guide / PS", "Touchpad click", "Mute / Misc1",
|
||||
"D-pad Up", "D-pad Down", "D-pad Left", "D-pad Right",
|
||||
"Left paddle (L4)", "Right paddle (R4)", "Left Fn (L5)", "Right Fn (R5)",
|
||||
"Extra C / Misc2", "Extra Z / Misc3", "Misc4", "Misc5", "Misc6"
|
||||
};
|
||||
static final int[] SRC_SEL = { -1, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0, 0,0,0,0, 0,0,0,0, 1,1,1,1,1 };
|
||||
static final int[] SRC_BIT = { -1, 0,1,2,3, 4,5,6,7, 8,9,10,11, 12,13,14, 15,16,17,18, 19,20,21,22, 0,1,2,3,4 };
|
||||
static final String[] PLAYER_NAMES = { "Off", "Player 1", "Player 2", "Player 3", "Player 4" };
|
||||
static final String[] AXIS_NAMES = { "Controller X (pitch)", "Controller Y (yaw)", "Controller Z (roll)" };
|
||||
static final String[] GYRO_INV_NAMES = { "None", "X", "Y", "Z", "X + Y", "X + Z", "Y + Z", "X + Y + Z" };
|
||||
|
||||
// ---- per-player settings (index 0..3) ----
|
||||
static final int[] touchMode = fill(TOUCH_SPLIT);
|
||||
static final int[][] remap = new int[PLAYERS][REMAP_COUNT];
|
||||
static final boolean[] touchInvX = new boolean[PLAYERS];
|
||||
static final boolean[] touchInvY = new boolean[PLAYERS];
|
||||
static final boolean[] touchSwap = new boolean[PLAYERS];
|
||||
static final int[] gyroGain = fill(100);
|
||||
static final int[] gyroInvert = new int[PLAYERS];
|
||||
static final int[] gyroDeadzone = new int[PLAYERS];
|
||||
static final float[][] gyroBias = new float[PLAYERS][3];
|
||||
static final int[][] gyroMap = new int[PLAYERS][3];
|
||||
static final boolean[] accelFollows = fill(true);
|
||||
static final int[] lightR = new int[PLAYERS];
|
||||
static final int[] lightG = new int[PLAYERS];
|
||||
static final int[] lightB = fill(255);
|
||||
static final int[] brightness = fill(100);
|
||||
static final int[] playerLed = new int[PLAYERS];
|
||||
|
||||
// ---- global settings ----
|
||||
// Auto by default: any SDL3-supported controller is used -- through SDL3's own USB driver when possible
|
||||
// (full features), otherwise through Android's input (e.g. Bluetooth). An Android duplicate of a controller
|
||||
// SDL3 already drives over USB is still ignored, so nothing is doubled.
|
||||
static volatile boolean forceUsb = false;
|
||||
static volatile boolean driverEnabled = true;
|
||||
static volatile int presentAs = 0;
|
||||
static final String[] PRESENT_NAMES = { "Steam Deck (default)", "DualSense (native)", "DualSense Edge (native)", "DualShock 4 (native)",
|
||||
"Steam Controller 2026 (native)", "Steam Controller 2015 (native)",
|
||||
"Steam Native Hook-up (Steam sees the real controller)" };
|
||||
// DroidDeck pad types: 0 Deck, 4 DualSense, 5 DualSense Edge, 3 DualShock 4, 1 Steam Controller 2026 (28de:1302),
|
||||
// 6 Steam Controller 2015 (28de:1102)
|
||||
// Hook-up hands USB controllers to Steam as themselves; any controller it can't (Bluetooth) stays a Deck pad.
|
||||
static final int[] PRESENT_PAD_TYPE = { 0, 4, 5, 3, 1, 6, 0 };
|
||||
static final int PRESENT_HOOKUP = 6;
|
||||
static boolean isHookup() { return presentAs == PRESENT_HOOKUP; }
|
||||
/** The "Present controller as" choice to go back to when hook-up is switched off from the bubble. */
|
||||
static volatile int lastPresentAs = 0;
|
||||
/** Was the SDL3 driver on before the bubble switched hook-up on? Switching hook-up off goes back to it. */
|
||||
static volatile boolean driverBeforeHookup = true;
|
||||
static final int PAD_TYPE_STEAM_2015 = 6;
|
||||
static boolean isSonyPadType(int t) { return t >= 3 && t <= 5; }
|
||||
static volatile int pollMs = 2;
|
||||
static final String[] RATE_NAMES = { "250 Hz (low CPU)", "500 Hz (recommended)", "1000 Hz (max)" };
|
||||
static final int[] RATE_MS = { 4, 2, 1 };
|
||||
static volatile boolean bubble = false;
|
||||
static volatile int bubbleX = 24, bubbleY = 160;
|
||||
|
||||
private static SharedPreferences prefs;
|
||||
|
||||
private Settings() {}
|
||||
|
||||
private static int[] fill(int v) { int[] a = new int[PLAYERS]; java.util.Arrays.fill(a, v); return a; }
|
||||
private static boolean[] fill(boolean v) { boolean[] a = new boolean[PLAYERS]; java.util.Arrays.fill(a, v); return a; }
|
||||
|
||||
static synchronized void init(Context c) {
|
||||
if (prefs != null) return;
|
||||
prefs = c.getApplicationContext().getSharedPreferences(Host.prefs(c, "bridge"), Context.MODE_PRIVATE);
|
||||
for (int p = 0; p < PLAYERS; p++) {
|
||||
String s = "_p" + p;
|
||||
touchMode[p] = clamp(prefs.getInt("touchMode" + s, TOUCH_SPLIT), 0, 2);
|
||||
for (int i = 0; i < REMAP_COUNT; i++) remap[p][i] = clamp(prefs.getInt("remap" + i + s, 0), 0, SRC_NAMES.length - 1);
|
||||
touchInvX[p] = prefs.getBoolean("touchInvX" + s, false);
|
||||
touchInvY[p] = prefs.getBoolean("touchInvY" + s, false);
|
||||
touchSwap[p] = prefs.getBoolean("touchSwap" + s, false);
|
||||
gyroGain[p] = clamp(prefs.getInt("gyroGain" + s, 100), 1, 800);
|
||||
gyroInvert[p] = clamp(prefs.getInt("gyroInvert" + s, 0), 0, 7);
|
||||
gyroDeadzone[p] = clamp(prefs.getInt("gyroDeadzone" + s, 0), 0, 50);
|
||||
gyroBias[p][0] = prefs.getFloat("gyroBiasX" + s, 0f);
|
||||
gyroBias[p][1] = prefs.getFloat("gyroBiasY" + s, 0f);
|
||||
gyroBias[p][2] = prefs.getFloat("gyroBiasZ" + s, 0f);
|
||||
for (int i = 0; i < 3; i++) gyroMap[p][i] = clamp(prefs.getInt("gyroMap" + i + s, i), 0, 2);
|
||||
accelFollows[p] = prefs.getBoolean("accelFollows" + s, true);
|
||||
lightR[p] = clamp(prefs.getInt("lightR" + s, 0), 0, 255);
|
||||
lightG[p] = clamp(prefs.getInt("lightG" + s, 0), 0, 255);
|
||||
lightB[p] = clamp(prefs.getInt("lightB" + s, 255), 0, 255);
|
||||
brightness[p] = clamp(prefs.getInt("brightness" + s, 100), 0, 100);
|
||||
playerLed[p] = clamp(prefs.getInt("playerLed" + s, 0), 0, 4);
|
||||
}
|
||||
forceUsb = prefs.getBoolean("forceUsbV2", false);
|
||||
driverEnabled = prefs.getBoolean("driverEnabled", true);
|
||||
presentAs = clamp(prefs.getInt("presentAs", 0), 0, PRESENT_NAMES.length - 1);
|
||||
lastPresentAs = clamp(prefs.getInt("lastPresentAs", 0), 0, PRESENT_NAMES.length - 1);
|
||||
if (lastPresentAs == PRESENT_HOOKUP) lastPresentAs = 0;
|
||||
driverBeforeHookup = prefs.getBoolean("driverBeforeHookup", true);
|
||||
pollMs = clamp(prefs.getInt("pollMs", 2), 1, 16);
|
||||
bubble = prefs.getBoolean("bubble", false);
|
||||
bubbleX = prefs.getInt("bubbleX", 24);
|
||||
bubbleY = prefs.getInt("bubbleY", 160);
|
||||
}
|
||||
|
||||
static void save() {
|
||||
SharedPreferences pr = prefs;
|
||||
if (pr == null) return;
|
||||
SharedPreferences.Editor e = pr.edit();
|
||||
for (int p = 0; p < PLAYERS; p++) {
|
||||
String s = "_p" + p;
|
||||
e.putInt("touchMode" + s, touchMode[p]);
|
||||
for (int i = 0; i < REMAP_COUNT; i++) e.putInt("remap" + i + s, remap[p][i]);
|
||||
e.putBoolean("touchInvX" + s, touchInvX[p]).putBoolean("touchInvY" + s, touchInvY[p]).putBoolean("touchSwap" + s, touchSwap[p]);
|
||||
e.putInt("gyroGain" + s, gyroGain[p]).putInt("gyroInvert" + s, gyroInvert[p]).putInt("gyroDeadzone" + s, gyroDeadzone[p]);
|
||||
e.putFloat("gyroBiasX" + s, gyroBias[p][0]).putFloat("gyroBiasY" + s, gyroBias[p][1]).putFloat("gyroBiasZ" + s, gyroBias[p][2]);
|
||||
for (int i = 0; i < 3; i++) e.putInt("gyroMap" + i + s, gyroMap[p][i]);
|
||||
e.putBoolean("accelFollows" + s, accelFollows[p]);
|
||||
e.putInt("lightR" + s, lightR[p]).putInt("lightG" + s, lightG[p]).putInt("lightB" + s, lightB[p]);
|
||||
e.putInt("brightness" + s, brightness[p]).putInt("playerLed" + s, playerLed[p]);
|
||||
}
|
||||
e.putBoolean("forceUsbV2", forceUsb);
|
||||
e.putBoolean("driverEnabled", driverEnabled);
|
||||
e.putInt("presentAs", presentAs);
|
||||
e.putInt("lastPresentAs", lastPresentAs);
|
||||
e.putBoolean("driverBeforeHookup", driverBeforeHookup);
|
||||
e.putInt("pollMs", pollMs);
|
||||
e.putBoolean("bubble", bubble).putInt("bubbleX", bubbleX).putInt("bubbleY", bubbleY);
|
||||
e.apply();
|
||||
}
|
||||
|
||||
private static int clamp(int v, int lo, int hi) { return Math.max(lo, Math.min(hi, v)); }
|
||||
|
||||
/** Is the source button [srcIndex] currently pressed, given the two button masks? */
|
||||
static boolean srcDown(int mask, int mask2, int srcIndex) {
|
||||
if (srcIndex <= 0 || srcIndex >= SRC_NAMES.length) return false;
|
||||
int m = SRC_SEL[srcIndex] == 1 ? mask2 : mask;
|
||||
return ((m >> SRC_BIT[srcIndex]) & 1) != 0;
|
||||
}
|
||||
|
||||
/** Applies the 4 grip remaps (targets 0..3) to the mask for player [p]; a mapped source stops acting as itself. */
|
||||
static int applyGripRemap(int mask, int mask2, int p) {
|
||||
if (p < 0 || p >= PLAYERS) p = 0;
|
||||
int[] rm = remap[p];
|
||||
int add = 0, consumed = 0;
|
||||
for (int t = 0; t < 4; t++) {
|
||||
int srcIndex = rm[t];
|
||||
if (srcDown(mask, mask2, srcIndex)) {
|
||||
add |= 1 << TARGET_BITS[t];
|
||||
if (SRC_SEL[srcIndex] == 0) consumed |= 1 << SRC_BIT[srcIndex];
|
||||
}
|
||||
}
|
||||
return (mask | add) & ~consumed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* Checks the GitHub Releases of the repo this APK was built in (CI writes assets/build.txt).
|
||||
* The repo must be public for the unauthenticated GitHub API to see its releases.
|
||||
*/
|
||||
final class UpdateChecker {
|
||||
interface Callback {
|
||||
/** url is non-null only when a newer build exists. Called on the main thread. */
|
||||
void onResult(String message, String url);
|
||||
}
|
||||
|
||||
static final class BuildInfo {
|
||||
String repo = "UNKNOWN", tag = "dev", sdl = "unknown";
|
||||
}
|
||||
|
||||
private UpdateChecker() {}
|
||||
|
||||
static BuildInfo readBuildInfo(Context ctx) {
|
||||
BuildInfo b = new BuildInfo();
|
||||
// Built into another app (SDL3DroidDeck), the bridge's build info has its own name next to that app's assets.
|
||||
try (InputStream in = ctx.getAssets().open(Host.embedded(ctx) ? "sdl3bridge-build.txt" : "build.txt");
|
||||
BufferedReader r = new BufferedReader(new InputStreamReader(in))) {
|
||||
String line;
|
||||
while ((line = r.readLine()) != null) {
|
||||
int eq = line.indexOf('=');
|
||||
if (eq <= 0) continue;
|
||||
String k = line.substring(0, eq).trim(), v = line.substring(eq + 1).trim();
|
||||
if (k.equals("repo")) b.repo = v;
|
||||
else if (k.equals("tag")) b.tag = v;
|
||||
else if (k.equals("sdl")) b.sdl = v;
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
return b;
|
||||
}
|
||||
|
||||
static void check(final Context ctx, final Callback cb) {
|
||||
final Handler main = new Handler(Looper.getMainLooper());
|
||||
final BuildInfo cur = readBuildInfo(ctx);
|
||||
new Thread(() -> {
|
||||
String msg;
|
||||
String url = null;
|
||||
if (Host.embedded(ctx)) {
|
||||
msg = "Built into " + Host.appName(ctx) + ": it updates together with it.";
|
||||
} else if (cur.repo.equals("UNKNOWN")) {
|
||||
msg = "Updates are off: this APK was not built by the GitHub workflow.";
|
||||
} else {
|
||||
try {
|
||||
HttpURLConnection c = (HttpURLConnection) new URL(
|
||||
"https://api.github.com/repos/" + cur.repo + "/releases/latest").openConnection();
|
||||
c.setConnectTimeout(8000);
|
||||
c.setReadTimeout(8000);
|
||||
c.setRequestProperty("Accept", "application/vnd.github+json");
|
||||
int code = c.getResponseCode();
|
||||
if (code == 404) {
|
||||
msg = "No release found. The repo must be public and have a finished build.";
|
||||
} else if (code != 200) {
|
||||
msg = "Update check failed (HTTP " + code + ").";
|
||||
} else {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
try (BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream()))) {
|
||||
String line;
|
||||
while ((line = r.readLine()) != null) sb.append(line);
|
||||
}
|
||||
JSONObject j = new JSONObject(sb.toString());
|
||||
String latest = j.optString("tag_name", "");
|
||||
String notes = j.optString("body", "");
|
||||
String sdl = "";
|
||||
int i = notes.indexOf("sdl=");
|
||||
if (i >= 0) sdl = notes.substring(i + 4).split("\\s")[0];
|
||||
String apk = null;
|
||||
JSONArray assets = j.optJSONArray("assets");
|
||||
for (int k = 0; assets != null && k < assets.length(); k++) {
|
||||
JSONObject a = assets.getJSONObject(k);
|
||||
if (a.optString("name").endsWith(".apk")) { apk = a.optString("browser_download_url"); break; }
|
||||
}
|
||||
if (apk != null && newer(latest, cur.tag)) {
|
||||
msg = "Update available: " + latest + (sdl.isEmpty() ? "" : " (SDL " + sdl + ")") + ". Tap to download.";
|
||||
url = apk;
|
||||
} else {
|
||||
msg = "Up to date (" + cur.tag + ", SDL " + cur.sdl + ").";
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
msg = "Update check failed: " + e.getClass().getSimpleName();
|
||||
}
|
||||
}
|
||||
final String m = msg;
|
||||
final String u = url;
|
||||
main.post(() -> cb.onResult(m, u));
|
||||
}, "update-check").start();
|
||||
}
|
||||
|
||||
/** Tags look like "build-12". Anything unparsable on our side ("dev") counts as older. */
|
||||
private static boolean newer(String latest, String current) {
|
||||
long a = number(latest), b = number(current);
|
||||
return a > b;
|
||||
}
|
||||
|
||||
private static long number(String tag) {
|
||||
try { return Long.parseLong(tag.replaceAll("[^0-9]", "")); } catch (NumberFormatException e) { return -1; }
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
|
||||
/**
|
||||
* Receives "controller plugged in" from Android. Accepting Android's prompt gives the bridge USB access to the
|
||||
* controller; nothing needs to be shown for that. The bridge's background service (with SDL3 in it) is started
|
||||
* if it isn't running yet, and picks the controller up; no screen opens.
|
||||
*/
|
||||
public class UsbAttachActivity extends Activity {
|
||||
@Override protected void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
// The bridge runs in its background service (SDL3 included): start that, nothing comes to the front.
|
||||
try {
|
||||
startForegroundService(new Intent(this, BridgeService.class));
|
||||
} catch (RuntimeException ignored) { }
|
||||
finish();
|
||||
overridePendingTransition(0, 0);
|
||||
}
|
||||
}
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
/*
|
||||
* Steam Native Hook-up fast path: direct access to DroidDeck's shared hook-up file (".hookup").
|
||||
*
|
||||
* DroidDeck passes the file to the bridge as a file descriptor (Android lets an app use a descriptor another
|
||||
* app hands it, only opening the other app's file by path is forbidden). The bridge then writes every HID
|
||||
* report of a hooked-up controller straight into the slot's input FIFO and wakes Steam's reader with a futex,
|
||||
* and takes Steam's output reports / feature reads from the slot itself -- no Java, no Binder message, no
|
||||
* polling on either side. DroidDeck still owns the slot (identity, sysfs, present flag); while the bridge
|
||||
* serves a slot it keeps the slot's direct_ms heartbeat fresh and DroidDeck leaves that slot's FIFOs alone.
|
||||
*
|
||||
* Plain C (no SDL / JNI) so it can be tested on Linux against the real fakeinput hook.
|
||||
* Layout must match HookupSlot in DroidDeck's hookup_native.inc and HookupBridge.kt.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <limits.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
|
||||
enum {
|
||||
HKS_MAGIC = 0x4b4f4f48,
|
||||
HKS_HEADER = 4096,
|
||||
HKS_SLOT = 53248,
|
||||
HKS_SLOTS = 4,
|
||||
HKS_SIZE = HKS_HEADER + HKS_SLOTS * HKS_SLOT,
|
||||
/* slot fields */
|
||||
HKS_PRESENT = 0,
|
||||
HKS_VENDOR = 8,
|
||||
HKS_PRODUCT = 10,
|
||||
HKS_IN_WRITE = 344,
|
||||
HKS_OUT_WRITE = 352,
|
||||
HKS_OUT_READ = 360,
|
||||
HKS_GET_REQUEST = 368,
|
||||
HKS_GET_REPLY = 376,
|
||||
HKS_GET_REPORT_ID = 384,
|
||||
HKS_GET_LENGTH = 388,
|
||||
HKS_GET = 392,
|
||||
HKS_DIRECT_MS = 520,
|
||||
HKS_RATE_HZ = 528, /* the bridge's poll rate: Steam's side hands Steam at most this many reports a second */
|
||||
HKS_IN = 5120,
|
||||
HKS_OUT = 41984,
|
||||
HKS_IN_FIFO = 256,
|
||||
HKS_OUT_FIFO = 64,
|
||||
HKS_ENTRY = 144,
|
||||
HKS_REPORT_MAX = 128
|
||||
};
|
||||
|
||||
#define HKS_FUTEX_WAKE 1 /* shared (not FUTEX_PRIVATE_FLAG): the waiter is Steam, another process */
|
||||
|
||||
typedef struct {
|
||||
uint8_t *base;
|
||||
int fd;
|
||||
uint64_t ino;
|
||||
} HkShm;
|
||||
|
||||
typedef struct {
|
||||
uint32_t kind; /* 0 output report, 1 feature report */
|
||||
int len;
|
||||
uint8_t data[HKS_REPORT_MAX];
|
||||
} HksOut;
|
||||
|
||||
static inline uint64_t hks_now_ms(void)
|
||||
{
|
||||
struct timespec t;
|
||||
clock_gettime(CLOCK_MONOTONIC, &t); /* = Android's SystemClock.uptimeMillis() clock */
|
||||
return (uint64_t)t.tv_sec * 1000u + (uint64_t)t.tv_nsec / 1000000u;
|
||||
}
|
||||
|
||||
/* Read time of an input report for DroidDeck's latency meter: CLOCK_MONOTONIC in us, low 32 bits, never 0. */
|
||||
static inline uint32_t hks_stamp_us(void)
|
||||
{
|
||||
struct timespec t;
|
||||
clock_gettime(CLOCK_MONOTONIC, &t);
|
||||
uint32_t us = (uint32_t)((uint64_t)t.tv_sec * 1000000u + (uint64_t)t.tv_nsec / 1000u);
|
||||
return us ? us : 1;
|
||||
}
|
||||
|
||||
static inline uint8_t *hks_slot(const HkShm *m, int i) { return m->base + HKS_HEADER + (size_t)i * HKS_SLOT; }
|
||||
static inline uint64_t *hks_u64(uint8_t *s, int off) { return (uint64_t *)(void *)(s + off); }
|
||||
static inline uint32_t *hks_u32(uint8_t *s, int off) { return (uint32_t *)(void *)(s + off); }
|
||||
|
||||
/* Maps the file behind fd (takes ownership of fd). 0 = ok, <0 = why not. */
|
||||
static inline int hks_map(HkShm *m, int fd)
|
||||
{
|
||||
struct stat st;
|
||||
if (fd < 0) return -1;
|
||||
if (fstat(fd, &st) != 0 || st.st_size < HKS_SIZE) { close(fd); return -2; }
|
||||
void *p = mmap(NULL, HKS_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
if (p == MAP_FAILED) { close(fd); return -3; }
|
||||
if (__atomic_load_n((uint32_t *)p, __ATOMIC_ACQUIRE) != HKS_MAGIC) { munmap(p, HKS_SIZE); close(fd); return -4; }
|
||||
m->base = (uint8_t *)p;
|
||||
m->fd = fd;
|
||||
m->ino = (uint64_t)st.st_ino;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static inline void hks_unmap(HkShm *m)
|
||||
{
|
||||
if (m->base) munmap(m->base, HKS_SIZE);
|
||||
if (m->fd >= 0) close(m->fd);
|
||||
m->base = NULL;
|
||||
m->fd = -1;
|
||||
m->ino = 0;
|
||||
}
|
||||
|
||||
/* Still DroidDeck's live file? (A new DroidDeck session deletes it and makes a new one.) */
|
||||
static inline int hks_alive(const HkShm *m)
|
||||
{
|
||||
struct stat st;
|
||||
return m->base && fstat(m->fd, &st) == 0 && st.st_nlink > 0;
|
||||
}
|
||||
|
||||
/* Does DroidDeck show this controller in slot i right now? Only then may the bridge serve the slot. */
|
||||
static inline int hks_owns(const HkShm *m, int i, uint16_t vid, uint16_t pid)
|
||||
{
|
||||
if (!m->base || i < 0 || i >= HKS_SLOTS) return 0;
|
||||
uint8_t *s = hks_slot(m, i);
|
||||
if (!__atomic_load_n(hks_u32(s, HKS_PRESENT), __ATOMIC_ACQUIRE)) return 0;
|
||||
uint16_t v, p;
|
||||
memcpy(&v, s + HKS_VENDOR, 2);
|
||||
memcpy(&p, s + HKS_PRODUCT, 2);
|
||||
return v == vid && p == pid;
|
||||
}
|
||||
|
||||
/* "The bridge serves this slot": DroidDeck and Steam's side read it (stale after ~1.5 s). */
|
||||
static inline void hks_heartbeat(const HkShm *m, int i, uint64_t now_ms)
|
||||
{
|
||||
__atomic_store_n(hks_u64(hks_slot(m, i), HKS_DIRECT_MS), now_ms, __ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
/* The rate Steam's side hands this slot's reports to Steam (the bridge's Poll rate setting; 0 = every report). */
|
||||
static inline void hks_set_rate(const HkShm *m, int i, uint32_t hz)
|
||||
{
|
||||
__atomic_store_n(hks_u32(hks_slot(m, i), HKS_RATE_HZ), hz, __ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
/* One input report (controller -> Steam): same protocol as HookupBridge.input(), then wake Steam's reader. */
|
||||
static inline void hks_write_in(const HkShm *m, int i, const uint8_t *data, int n)
|
||||
{
|
||||
uint8_t *s = hks_slot(m, i);
|
||||
uint64_t *write = hks_u64(s, HKS_IN_WRITE);
|
||||
uint64_t idx = __atomic_load_n(write, __ATOMIC_RELAXED);
|
||||
uint8_t *e = s + HKS_IN + (size_t)(idx % HKS_IN_FIFO) * HKS_ENTRY;
|
||||
if (n < 0) n = 0;
|
||||
if (n > HKS_REPORT_MAX) n = HKS_REPORT_MAX;
|
||||
__atomic_store_n(hks_u64(e, 0), 0, __ATOMIC_RELAXED);
|
||||
__atomic_thread_fence(__ATOMIC_RELEASE);
|
||||
__atomic_store_n(hks_u32(e, 8), (uint32_t)n, __ATOMIC_RELAXED);
|
||||
__atomic_store_n(hks_u32(e, 12), hks_stamp_us(), __ATOMIC_RELAXED); /* when the bridge read it: latency meter */
|
||||
memcpy(e + 16, data, (size_t)n);
|
||||
__atomic_thread_fence(__ATOMIC_RELEASE);
|
||||
__atomic_store_n(hks_u64(e, 0), idx + 1, __ATOMIC_RELEASE);
|
||||
__atomic_store_n(write, idx + 1, __ATOMIC_RELEASE);
|
||||
/* Steam's reader sleeps on the low half of in_write (little endian). */
|
||||
syscall(SYS_futex, (uint32_t *)(void *)write, HKS_FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
|
||||
}
|
||||
|
||||
/* Takes up to max queued reports Steam wrote (rumble, lights, settings). */
|
||||
static inline int hks_take_out(const HkShm *m, int i, HksOut *out, int max)
|
||||
{
|
||||
uint8_t *s = hks_slot(m, i);
|
||||
uint64_t read = __atomic_load_n(hks_u64(s, HKS_OUT_READ), __ATOMIC_ACQUIRE);
|
||||
uint64_t written = __atomic_load_n(hks_u64(s, HKS_OUT_WRITE), __ATOMIC_ACQUIRE);
|
||||
int n = 0;
|
||||
while (read < written && n < max) {
|
||||
uint8_t *e = s + HKS_OUT + (size_t)(read % HKS_OUT_FIFO) * HKS_ENTRY;
|
||||
if (__atomic_load_n(hks_u64(e, 0), __ATOMIC_ACQUIRE) != read + 1) break; /* still being written */
|
||||
uint32_t len = __atomic_load_n(hks_u32(e, 8), __ATOMIC_RELAXED);
|
||||
if (len > HKS_REPORT_MAX) len = HKS_REPORT_MAX;
|
||||
out[n].len = (int)len;
|
||||
out[n].kind = __atomic_load_n(hks_u32(e, 12), __ATOMIC_RELAXED);
|
||||
memcpy(out[n].data, e + 16, len);
|
||||
n++;
|
||||
read++;
|
||||
}
|
||||
__atomic_store_n(hks_u64(s, HKS_OUT_READ), read, __ATOMIC_RELEASE);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* A feature / input report read Steam is waiting for? (1 = yes; *last remembers what was taken.) */
|
||||
static inline int hks_get_pending(const HkShm *m, int i, uint64_t *last, uint64_t *request, int *report_id,
|
||||
int *input, int *length)
|
||||
{
|
||||
uint8_t *s = hks_slot(m, i);
|
||||
uint64_t r = __atomic_load_n(hks_u64(s, HKS_GET_REQUEST), __ATOMIC_ACQUIRE);
|
||||
if (r == *last || r == __atomic_load_n(hks_u64(s, HKS_GET_REPLY), __ATOMIC_ACQUIRE)) return 0;
|
||||
*last = r;
|
||||
uint32_t word = __atomic_load_n(hks_u32(s, HKS_GET_REPORT_ID), __ATOMIC_RELAXED);
|
||||
int32_t len;
|
||||
memcpy(&len, s + HKS_GET_LENGTH, 4);
|
||||
*request = r;
|
||||
*report_id = (int)(word & 0xff);
|
||||
*input = (int)((word >> 8) & 1);
|
||||
*length = len < 1 ? 1 : len > HKS_REPORT_MAX ? HKS_REPORT_MAX : len;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Answer to that read (n <= 0: it failed). */
|
||||
static inline void hks_get_reply(const HkShm *m, int i, uint64_t request, const uint8_t *data, int n)
|
||||
{
|
||||
uint8_t *s = hks_slot(m, i);
|
||||
if (n < 0 || !data) n = 0;
|
||||
if (n > HKS_REPORT_MAX) n = HKS_REPORT_MAX;
|
||||
if (n) memcpy(s + HKS_GET, data, (size_t)n);
|
||||
int32_t len = n;
|
||||
__atomic_store_n((int32_t *)(void *)(s + HKS_GET_LENGTH), len, __ATOMIC_RELAXED);
|
||||
__atomic_store_n(hks_u64(s, HKS_GET_REPLY), request, __ATOMIC_RELEASE);
|
||||
}
|
||||
+714
@@ -0,0 +1,714 @@
|
||||
/*
|
||||
* "Steam Native Hook-up": instead of reading a controller as a gamepad and re-presenting it, hand Steam the
|
||||
* REAL controller. SDL3 is still used to find out which USB HID interface is a game controller (any
|
||||
* controller SDL3's USB driver supports); that interface is then released by SDL's gamepad layer and opened
|
||||
* raw, and every HID report travels unchanged between the controller and DroidDeck's hidraw node -- with the
|
||||
* controller's real vendor/product id, name, serial and report descriptor -- so Steam's own driver for that
|
||||
* controller runs, exactly like on a PC: a Vader 4 Pro with its back buttons, C/Z and gyro, a DualSense Edge
|
||||
* with its touchpad, mute, paddles and Fn buttons, an Xbox controller, a Switch Pro controller, ...
|
||||
*
|
||||
* Controllers SDL3 can only reach through Android's input (Bluetooth) cannot be handed over raw; they keep
|
||||
* working as before (DroidDeck's Steam Deck pad). Included once from main.c; SDL_hid calls run on the SDL thread.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <pthread.h>
|
||||
#include <sys/resource.h>
|
||||
#include "hkshm.h"
|
||||
|
||||
#define HOOKUP_SLOTS 4
|
||||
#define HOOKUP_REPORT_MAX 128
|
||||
|
||||
typedef struct {
|
||||
SDL_hid_device *dev;
|
||||
char path[256];
|
||||
Uint16 vid, pid;
|
||||
int iface;
|
||||
} HookupDev;
|
||||
|
||||
static HookupDev g_hk[HOOKUP_SLOTS];
|
||||
static _Atomic int g_hookup_on;
|
||||
static _Atomic int g_hookup_held; /* on, but waiting for Steam (DroidDeck's desktop without Steam running) */
|
||||
static int g_hookup_applied = -1; /* last mode the SDL thread acted on */
|
||||
static char g_hk_types[1024]; /* "0xVVVV/0xPPPP,..." controller types handed to Steam */
|
||||
static int g_hk_iface_of_type[32]; /* interface number SDL used, per entry in g_hk_types (index order) */
|
||||
static Uint16 g_hk_type_vid[32], g_hk_type_pid[32];
|
||||
static int g_hk_type_count;
|
||||
static Uint64 g_hk_scan_ms;
|
||||
static Uint32 g_hk_changes = 0xffffffffu;
|
||||
static jmethodID g_hk_added, g_hk_input, g_hk_removed, g_hk_reply, g_hk_prefetch, g_hk_log;
|
||||
|
||||
/* ---- fast path (hkshm.h): reports go straight into DroidDeck's shared file, read by a dedicated thread ----
|
||||
* g_hk_io is held by the reader thread for each pass over the controllers, and by anyone who remaps the file
|
||||
* or releases a controller, so neither disappears under the reader. */
|
||||
static HkShm g_hks = { NULL, -1, 0 };
|
||||
static pthread_mutex_t g_hk_io = PTHREAD_MUTEX_INITIALIZER;
|
||||
/* Held by the writer thread while it uses the controllers (its USB writes can take a few ms, so not under g_hk_io);
|
||||
* releasing a controller takes it first. Order: g_hk_wr, then g_hk_io. */
|
||||
static pthread_mutex_t g_hk_wr = PTHREAD_MUTEX_INITIALIZER;
|
||||
static _Atomic int g_hk_writer_started;
|
||||
static _Atomic int g_hk_gone[HOOKUP_SLOTS]; /* reader saw the controller go away; SDL thread closes it */
|
||||
static _Atomic int g_hk_reader_started;
|
||||
static _Atomic int g_hk_fast_now[HOOKUP_SLOTS]; /* slot currently served through the shared file */
|
||||
static int g_hk_fast_logged[HOOKUP_SLOTS]; /* SDL thread: last fast/slow state logged per slot */
|
||||
static uint64_t g_hk_get_last[HOOKUP_SLOTS]; /* writer thread: last feature read taken from the file */
|
||||
static Uint64 g_hk_alive_ms;
|
||||
|
||||
/* Logged to logcat AND sent to DroidDeck, which writes it into the session's pad.log ("sdl3bridge: ..."). */
|
||||
static void hk_log(JNIEnv *env, const char *fmt, ...)
|
||||
{
|
||||
char line[400];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(line, sizeof(line), fmt, ap);
|
||||
va_end(ap);
|
||||
SDL_Log("%s", line);
|
||||
if (env && g_hk_log) {
|
||||
jstring s = (*env)->NewStringUTF(env, line);
|
||||
if (s) {
|
||||
(*env)->CallStaticVoidMethod(env, g_cls, g_hk_log, s);
|
||||
(*env)->DeleteLocalRef(env, s);
|
||||
}
|
||||
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- requests from Java (any thread) -> SDL thread ---- */
|
||||
enum { HK_OUT = 0, HK_FEATURE_SET = 1, HK_GET_FEATURE = 2, HK_GET_INPUT = 3 };
|
||||
typedef struct {
|
||||
int slot, type, len;
|
||||
jlong request;
|
||||
Uint8 data[HOOKUP_REPORT_MAX];
|
||||
} HookupReq;
|
||||
#define HK_QUEUE 128
|
||||
static HookupReq g_hk_queue[HK_QUEUE];
|
||||
static int g_hk_head, g_hk_tail;
|
||||
static SDL_SpinLock g_hk_lock;
|
||||
|
||||
static void hk_push(int slot, int type, const Uint8 *data, int len, jlong request)
|
||||
{
|
||||
if (slot < 0 || slot >= HOOKUP_SLOTS) return;
|
||||
if (len < 0) len = 0;
|
||||
if (len > HOOKUP_REPORT_MAX) len = HOOKUP_REPORT_MAX;
|
||||
SDL_LockSpinlock(&g_hk_lock);
|
||||
int next = (g_hk_tail + 1) % HK_QUEUE;
|
||||
if (next != g_hk_head) {
|
||||
HookupReq *r = &g_hk_queue[g_hk_tail];
|
||||
r->slot = slot; r->type = type; r->len = len; r->request = request;
|
||||
if (len) memcpy(r->data, data, (size_t)len);
|
||||
g_hk_tail = next;
|
||||
}
|
||||
SDL_UnlockSpinlock(&g_hk_lock);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_example_dsedge_NativeBridge_nativeSetHookup(JNIEnv *env, jclass c, jint on)
|
||||
{
|
||||
(void)env; (void)c;
|
||||
atomic_store(&g_hookup_held, on == 2); /* DroidDeck's desktop without Steam: wait (controllers stay gamepads) */
|
||||
atomic_store(&g_hookup_on, on == 1);
|
||||
}
|
||||
|
||||
/* DroidDeck handed over its shared hook-up file (any thread). Returns 0 when the fast path is on. */
|
||||
JNIEXPORT jint JNICALL Java_com_example_dsedge_NativeBridge_nativeHookupMapShm(JNIEnv *env, jclass c, jint fd)
|
||||
{
|
||||
(void)c;
|
||||
HkShm m = { NULL, -1, 0 };
|
||||
int r = hks_map(&m, fd);
|
||||
pthread_mutex_lock(&g_hk_io);
|
||||
int same = r == 0 && g_hks.base && g_hks.ino == m.ino && hks_alive(&g_hks);
|
||||
if (r == 0 && !same) {
|
||||
hks_unmap(&g_hks);
|
||||
g_hks = m;
|
||||
}
|
||||
pthread_mutex_unlock(&g_hk_io);
|
||||
if (same) hks_unmap(&m); /* already mapped: keep the old mapping */
|
||||
if (r == 0 && !same)
|
||||
hk_log(env, "hookup: fast path on: reports go straight into DroidDeck's shared memory (no messages, Steam woken at once)");
|
||||
else if (r != 0)
|
||||
hk_log(env, "hookup: fast path unavailable (shared file could not be mapped, %d); using messages", r);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Inode of the mapped live file (0: none) -- DroidDeck compares it with its own file to know if it must resend. */
|
||||
JNIEXPORT jlong JNICALL Java_com_example_dsedge_NativeBridge_nativeHookupShmInode(JNIEnv *env, jclass c)
|
||||
{
|
||||
(void)env; (void)c;
|
||||
pthread_mutex_lock(&g_hk_io);
|
||||
jlong ino = hks_alive(&g_hks) ? (jlong)g_hks.ino : 0;
|
||||
pthread_mutex_unlock(&g_hk_io);
|
||||
return ino;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_example_dsedge_NativeBridge_nativeHookupOutput(JNIEnv *env, jclass c, jint slot, jint kind, jbyteArray data)
|
||||
{
|
||||
(void)c;
|
||||
if (!data) return;
|
||||
jsize n = (*env)->GetArrayLength(env, data);
|
||||
if (n < 1) return;
|
||||
Uint8 buf[HOOKUP_REPORT_MAX];
|
||||
if (n > HOOKUP_REPORT_MAX) n = HOOKUP_REPORT_MAX;
|
||||
(*env)->GetByteArrayRegion(env, data, 0, n, (jbyte *)buf);
|
||||
hk_push(slot, kind == 1 ? HK_FEATURE_SET : HK_OUT, buf, (int)n, 0);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_example_dsedge_NativeBridge_nativeHookupGet(JNIEnv *env, jclass c, jint slot, jlong request,
|
||||
jint reportId, jboolean input, jint length)
|
||||
{
|
||||
(void)env; (void)c;
|
||||
Uint8 buf[2] = { (Uint8)reportId, (Uint8)(length > HOOKUP_REPORT_MAX ? HOOKUP_REPORT_MAX : length < 1 ? 1 : length) };
|
||||
hk_push(slot, input ? HK_GET_INPUT : HK_GET_FEATURE, buf, 2, request);
|
||||
}
|
||||
|
||||
/* ---- SDL thread -> Java ---- */
|
||||
static void hk_java_init(JNIEnv *env)
|
||||
{
|
||||
if (g_hk_added) return;
|
||||
g_hk_added = (*env)->GetStaticMethodID(env, g_cls, "onHookupAdded", "(ILjava/lang/String;III)V");
|
||||
g_hk_input = (*env)->GetStaticMethodID(env, g_cls, "onHookupInput", "(I[B)V");
|
||||
g_hk_removed = (*env)->GetStaticMethodID(env, g_cls, "onHookupRemoved", "(I)V");
|
||||
g_hk_reply = (*env)->GetStaticMethodID(env, g_cls, "onHookupReply", "(IJ[B)V");
|
||||
g_hk_prefetch = (*env)->GetStaticMethodID(env, g_cls, "prefetchHookupDescriptor", "(Ljava/lang/String;)V");
|
||||
g_hk_log = (*env)->GetStaticMethodID(env, g_cls, "onBridgeLog", "(Ljava/lang/String;)V");
|
||||
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
|
||||
}
|
||||
|
||||
static jbyteArray hk_bytes(JNIEnv *env, const Uint8 *data, int len)
|
||||
{
|
||||
if (!data || len <= 0) return NULL;
|
||||
jbyteArray arr = (*env)->NewByteArray(env, len);
|
||||
if (arr) (*env)->SetByteArrayRegion(env, arr, 0, len, (const jbyte *)data);
|
||||
return arr;
|
||||
}
|
||||
|
||||
static bool hookup_active(void)
|
||||
{
|
||||
for (int i = 0; i < HOOKUP_SLOTS; i++) if (g_hk[i].dev) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
static int hookup_count(void)
|
||||
{
|
||||
int n = 0;
|
||||
for (int i = 0; i < HOOKUP_SLOTS; i++) if (g_hk[i].dev) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
/* Hooked-up controllers whose reports currently go straight into DroidDeck's shared memory. */
|
||||
static int hookup_fast_count(void)
|
||||
{
|
||||
int n = 0;
|
||||
for (int i = 0; i < HOOKUP_SLOTS; i++) if (g_hk[i].dev && atomic_load(&g_hk_fast_now[i])) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
static void hk_close(JNIEnv *env, int i, const char *why)
|
||||
{
|
||||
if (!g_hk[i].dev) return;
|
||||
hk_log(env, "hookup: slot %d %04x:%04x released (%s)", i, g_hk[i].vid, g_hk[i].pid, why);
|
||||
pthread_mutex_lock(&g_hk_wr); /* the writer thread is not using it now, and won't see it again */
|
||||
pthread_mutex_lock(&g_hk_io); /* nor is the reader thread */
|
||||
SDL_hid_device *dev = g_hk[i].dev;
|
||||
memset(&g_hk[i], 0, sizeof(g_hk[i]));
|
||||
atomic_store(&g_hk_gone[i], 0);
|
||||
atomic_store(&g_hk_fast_now[i], 0);
|
||||
pthread_mutex_unlock(&g_hk_io);
|
||||
pthread_mutex_unlock(&g_hk_wr);
|
||||
g_hk_fast_logged[i] = 0;
|
||||
SDL_hid_close(dev);
|
||||
if (g_hk_removed) (*env)->CallStaticVoidMethod(env, g_cls, g_hk_removed, (jint)i);
|
||||
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
|
||||
}
|
||||
|
||||
static bool hk_path_open(const char *path)
|
||||
{
|
||||
for (int i = 0; i < HOOKUP_SLOTS; i++) if (g_hk[i].dev && !strcmp(g_hk[i].path, path)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* Reader thread: takes each report the moment SDL's USB thread has queued it (checked every 250 us instead of
|
||||
* once per main-loop pass) and writes it straight into Steam's FIFO, waking Steam's reader. When the fast path
|
||||
* is not available for a slot, the report goes the old way (Java -> message to DroidDeck).
|
||||
*/
|
||||
static int SDLCALL hk_reader(void *unused)
|
||||
{
|
||||
(void)unused;
|
||||
JNIEnv *env = (JNIEnv *)SDL_GetAndroidJNIEnv();
|
||||
setpriority(PRIO_PROCESS, (id_t)syscall(SYS_gettid), -10); /* like Android's URGENT_DISPLAY; ignored if refused */
|
||||
/* Latency meter, every controller: do reports come from Android's USB layer one by one, or in bursts (several
|
||||
* waiting at once = they were held up before the bridge got them)? Logged every 10 s: the first time, then
|
||||
* when bursts or long gaps show up. */
|
||||
uint32_t m_reports[HOOKUP_SLOTS] = {0}, m_passes[HOOKUP_SLOTS] = {0}, m_burst[HOOKUP_SLOTS] = {0};
|
||||
uint64_t m_last_us[HOOKUP_SLOTS] = {0}, m_gap_us[HOOKUP_SLOTS] = {0}, m_since_us = 0;
|
||||
int m_logged[HOOKUP_SLOTS] = {0};
|
||||
for (;;) {
|
||||
int got = 0, any = 0;
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
uint64_t now_us = (uint64_t)ts.tv_sec * 1000000u + (uint64_t)ts.tv_nsec / 1000u;
|
||||
pthread_mutex_lock(&g_hk_io);
|
||||
for (int i = 0; i < HOOKUP_SLOTS; i++) {
|
||||
SDL_hid_device *dev = g_hk[i].dev;
|
||||
if (!dev || atomic_load(&g_hk_gone[i])) continue;
|
||||
any = 1;
|
||||
int fast = hks_owns(&g_hks, i, g_hk[i].vid, g_hk[i].pid);
|
||||
atomic_store(&g_hk_fast_now[i], fast);
|
||||
uint32_t pass = 0;
|
||||
for (int reads = 0; reads < 64; reads++) {
|
||||
Uint8 buf[HOOKUP_REPORT_MAX];
|
||||
int n = SDL_hid_read(dev, buf, sizeof(buf));
|
||||
if (n == 0) break;
|
||||
if (n < 0) { atomic_store(&g_hk_gone[i], 1); break; }
|
||||
got++;
|
||||
pass++;
|
||||
if (fast) {
|
||||
hks_write_in(&g_hks, i, buf, n);
|
||||
} else if (env && g_hk_input) {
|
||||
jbyteArray arr = hk_bytes(env, buf, n);
|
||||
if (arr) (*env)->CallStaticVoidMethod(env, g_cls, g_hk_input, (jint)i, arr);
|
||||
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
|
||||
if (arr) (*env)->DeleteLocalRef(env, arr);
|
||||
}
|
||||
}
|
||||
if (pass) {
|
||||
m_reports[i] += pass;
|
||||
m_passes[i]++;
|
||||
if (pass > m_burst[i]) m_burst[i] = pass;
|
||||
if (m_last_us[i] && now_us - m_last_us[i] > m_gap_us[i]) m_gap_us[i] = now_us - m_last_us[i];
|
||||
m_last_us[i] = now_us;
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&g_hk_io);
|
||||
if (!m_since_us) m_since_us = now_us;
|
||||
if (now_us - m_since_us >= 10000000u) {
|
||||
double secs = (now_us - m_since_us) / 1e6;
|
||||
for (int i = 0; i < HOOKUP_SLOTS; i++) {
|
||||
if (!m_passes[i]) continue;
|
||||
if (env && (!m_logged[i]++ || m_burst[i] > 2 || m_gap_us[i] > 8000))
|
||||
hk_log(env, "latency: slot %d: %.0f reports/s from USB, up to %u waiting at once (avg %.2f), "
|
||||
"longest gap %.1f ms", i, m_reports[i] / secs, m_burst[i],
|
||||
(double)m_reports[i] / m_passes[i], m_gap_us[i] / 1000.0);
|
||||
m_reports[i] = m_passes[i] = m_burst[i] = 0;
|
||||
m_gap_us[i] = 0;
|
||||
}
|
||||
m_since_us = now_us;
|
||||
}
|
||||
if (!got) {
|
||||
struct timespec t = { 0, any ? 250000L : 20000000L }; /* 250 us while controllers are handed over */
|
||||
nanosleep(&t, NULL);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Writer thread: Steam's output reports (rumble, lights, settings) and feature reads for the slots the bridge
|
||||
* serves through the shared file, sent to the controller as soon as Steam queues them (checked every 500 us).
|
||||
* Each USB write takes a few ms; done in the SDL main loop they waited for its next pass and for each other,
|
||||
* so under heavy rumble Steam's queue filled up and Steam had to wait for room.
|
||||
*/
|
||||
static int SDLCALL hk_writer(void *unused)
|
||||
{
|
||||
(void)unused;
|
||||
setpriority(PRIO_PROCESS, (id_t)syscall(SYS_gettid), -10);
|
||||
for (;;) {
|
||||
int did = 0, any = 0;
|
||||
pthread_mutex_lock(&g_hk_wr);
|
||||
for (int i = 0; i < HOOKUP_SLOTS; i++) {
|
||||
HksOut outs[16];
|
||||
int nout = 0, want_get = 0, report_id = 0, input = 0, length = 0;
|
||||
uint64_t request = 0;
|
||||
pthread_mutex_lock(&g_hk_io);
|
||||
SDL_hid_device *dev = g_hk[i].dev;
|
||||
if (dev && !atomic_load(&g_hk_gone[i]) && hks_owns(&g_hks, i, g_hk[i].vid, g_hk[i].pid)) {
|
||||
nout = hks_take_out(&g_hks, i, outs, (int)SDL_arraysize(outs));
|
||||
want_get = hks_get_pending(&g_hks, i, &g_hk_get_last[i], &request, &report_id, &input, &length);
|
||||
}
|
||||
pthread_mutex_unlock(&g_hk_io);
|
||||
if (!dev) continue;
|
||||
any = 1;
|
||||
for (int k = 0; k < nout; k++) {
|
||||
if (outs[k].kind == 1) SDL_hid_send_feature_report(dev, outs[k].data, (size_t)outs[k].len);
|
||||
else SDL_hid_write(dev, outs[k].data, (size_t)outs[k].len);
|
||||
}
|
||||
if (want_get) {
|
||||
Uint8 buf[HOOKUP_REPORT_MAX + 1] = { 0 };
|
||||
buf[0] = (Uint8)report_id;
|
||||
int n = input ? SDL_hid_get_input_report(dev, buf, (size_t)length)
|
||||
: SDL_hid_get_feature_report(dev, buf, (size_t)length);
|
||||
pthread_mutex_lock(&g_hk_io);
|
||||
if (hks_owns(&g_hks, i, g_hk[i].vid, g_hk[i].pid)) hks_get_reply(&g_hks, i, request, buf, n);
|
||||
pthread_mutex_unlock(&g_hk_io);
|
||||
}
|
||||
did += nout + want_get;
|
||||
}
|
||||
pthread_mutex_unlock(&g_hk_wr);
|
||||
if (!did) {
|
||||
struct timespec t = { 0, any ? 500000L : 20000000L };
|
||||
nanosleep(&t, NULL);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void hk_start_reader(void)
|
||||
{
|
||||
if (!atomic_exchange(&g_hk_writer_started, 1)) {
|
||||
SDL_Thread *w = SDL_CreateThread(hk_writer, "hookup-writer", NULL);
|
||||
if (w) SDL_DetachThread(w);
|
||||
else atomic_store(&g_hk_writer_started, 0);
|
||||
}
|
||||
if (atomic_exchange(&g_hk_reader_started, 1)) return;
|
||||
SDL_Thread *t = SDL_CreateThread(hk_reader, "hookup-reader", NULL);
|
||||
if (t) SDL_DetachThread(t);
|
||||
else atomic_store(&g_hk_reader_started, 0);
|
||||
}
|
||||
|
||||
/* SDL thread, every loop: the heartbeat that tells DroidDeck and Steam's side the bridge serves the slot itself. */
|
||||
static void hk_serve_fast(JNIEnv *env)
|
||||
{
|
||||
uint64_t now = hks_now_ms();
|
||||
for (int i = 0; i < HOOKUP_SLOTS; i++) {
|
||||
if (!g_hk[i].dev) continue;
|
||||
pthread_mutex_lock(&g_hk_io);
|
||||
int fast = hks_owns(&g_hks, i, g_hk[i].vid, g_hk[i].pid);
|
||||
if (fast) {
|
||||
hks_heartbeat(&g_hks, i, now);
|
||||
int ms = atomic_load(&g_poll_ms);
|
||||
hks_set_rate(&g_hks, i, ms > 0 ? (uint32_t)(1000 / ms) : 0u); /* Poll rate also paces Hook-up */
|
||||
}
|
||||
pthread_mutex_unlock(&g_hk_io);
|
||||
if (fast != g_hk_fast_logged[i]) {
|
||||
g_hk_fast_logged[i] = fast;
|
||||
if (fast) hk_log(env, "hookup: slot %d served through shared memory (fast path)", i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int hk_free_slot(void)
|
||||
{
|
||||
for (int i = 0; i < HOOKUP_SLOTS; i++) if (!g_hk[i].dev) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Read the HID report descriptor while nobody holds the interface (Android refuses an interface request on an
|
||||
* interface another connection has claimed), so Steam gets the controller's real one. */
|
||||
static void hk_prefetch(JNIEnv *env, const char *path)
|
||||
{
|
||||
if (!g_hk_prefetch) return;
|
||||
jstring p = (*env)->NewStringUTF(env, path);
|
||||
(*env)->CallStaticVoidMethod(env, g_cls, g_hk_prefetch, p);
|
||||
(*env)->DeleteLocalRef(env, p);
|
||||
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
|
||||
}
|
||||
|
||||
static bool hk_adopt(JNIEnv *env, int slot, SDL_hid_device *dev, const char *path, Uint16 vid, Uint16 pid, int iface);
|
||||
|
||||
static bool hk_open(JNIEnv *env, const char *path, Uint16 vid, Uint16 pid, int iface)
|
||||
{
|
||||
if (hk_path_open(path)) return true;
|
||||
int slot = hk_free_slot();
|
||||
if (slot < 0) return false;
|
||||
hk_prefetch(env, path);
|
||||
SDL_hid_device *dev = SDL_hid_open_path(path);
|
||||
if (!dev) {
|
||||
hk_log(env, "hookup: could not open %s: %s", path, SDL_GetError());
|
||||
return false;
|
||||
}
|
||||
SDL_hid_set_nonblocking(dev, 1);
|
||||
return hk_adopt(env, slot, dev, path, vid, pid, iface);
|
||||
}
|
||||
|
||||
/* A raw-opened controller interface becomes hook-up slot `slot` (reader thread + DroidDeck's hidraw node). */
|
||||
static bool hk_adopt(JNIEnv *env, int slot, SDL_hid_device *dev, const char *path, Uint16 vid, Uint16 pid, int iface)
|
||||
{
|
||||
pthread_mutex_lock(&g_hk_io);
|
||||
SDL_strlcpy(g_hk[slot].path, path, sizeof(g_hk[slot].path));
|
||||
g_hk[slot].vid = vid;
|
||||
g_hk[slot].pid = pid;
|
||||
g_hk[slot].iface = iface;
|
||||
atomic_store(&g_hk_gone[slot], 0);
|
||||
g_hk_get_last[slot] = 0;
|
||||
g_hk[slot].dev = dev;
|
||||
pthread_mutex_unlock(&g_hk_io);
|
||||
hk_start_reader();
|
||||
hk_log(env, "hookup: slot %d is %04x:%04x interface %d (%s), handing it to DroidDeck", slot, vid, pid, iface, path);
|
||||
if (g_hk_added) {
|
||||
jstring p = (*env)->NewStringUTF(env, path);
|
||||
(*env)->CallStaticVoidMethod(env, g_cls, g_hk_added, (jint)slot, p, (jint)vid, (jint)pid, (jint)iface);
|
||||
(*env)->DeleteLocalRef(env, p);
|
||||
if ((*env)->ExceptionCheck(env)) {
|
||||
(*env)->ExceptionDescribe(env);
|
||||
(*env)->ExceptionClear(env);
|
||||
hk_log(env, "hookup: slot %d: describing the controller to DroidDeck failed (Java exception, see logcat)", slot);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* SDL's gamepad layer must let go of the hooked-up controller types: the ignore hint (which also keeps the
|
||||
* Steam Controller 2026, passed through by triton.h, away) plus a restart of the gamepad subsystem. */
|
||||
static void hk_apply_ignore_list(JNIEnv *env)
|
||||
{
|
||||
char hint[1200] = "0x28de/0x1302,0x28de/0x1304,0x28de/0x1305";
|
||||
if (atomic_load(&g_hookup_on) && g_hk_types[0]) {
|
||||
SDL_strlcat(hint, ",", sizeof(hint));
|
||||
SDL_strlcat(hint, g_hk_types, sizeof(hint));
|
||||
}
|
||||
SDL_SetHint(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES, hint);
|
||||
}
|
||||
|
||||
static bool hk_type_known(Uint16 vid, Uint16 pid)
|
||||
{
|
||||
for (int i = 0; i < g_hk_type_count; i++) if (g_hk_type_vid[i] == vid && g_hk_type_pid[i] == pid) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
static void hk_add_type(Uint16 vid, Uint16 pid, int iface)
|
||||
{
|
||||
if (hk_type_known(vid, pid) || g_hk_type_count >= (int)SDL_arraysize(g_hk_type_vid)) return;
|
||||
char one[24];
|
||||
snprintf(one, sizeof(one), "%s0x%04x/0x%04x", g_hk_types[0] ? "," : "", vid, pid);
|
||||
SDL_strlcat(g_hk_types, one, sizeof(g_hk_types));
|
||||
g_hk_type_vid[g_hk_type_count] = vid;
|
||||
g_hk_type_pid[g_hk_type_count] = pid;
|
||||
g_hk_iface_of_type[g_hk_type_count] = iface;
|
||||
g_hk_type_count++;
|
||||
}
|
||||
|
||||
static int hk_type_iface(Uint16 vid, Uint16 pid)
|
||||
{
|
||||
for (int i = 0; i < g_hk_type_count; i++) if (g_hk_type_vid[i] == vid && g_hk_type_pid[i] == pid) return g_hk_iface_of_type[i];
|
||||
return -1;
|
||||
}
|
||||
|
||||
static void restart_gamepads(JNIEnv *env); /* main.c */
|
||||
|
||||
/* Interface number of an SDL hid path ("<usb device>/<vid>/<pid>/<interface index>" on Android). */
|
||||
static int hk_path_iface(const char *path)
|
||||
{
|
||||
const char *slash = strrchr(path, '/');
|
||||
return slash ? SDL_atoi(slash + 1) : 0;
|
||||
}
|
||||
|
||||
/* Hand every SDL3 USB-driver gamepad (and later copies of those controller types) over to Steam. */
|
||||
static void hookup_take_gamepads(JNIEnv *env)
|
||||
{
|
||||
bool handed = false;
|
||||
int cnt = 0;
|
||||
SDL_JoystickID *ids = SDL_GetGamepads(&cnt);
|
||||
for (int i = 0; ids && i < cnt; i++) {
|
||||
const char *path = SDL_GetGamepadPathForID(ids[i]);
|
||||
if (!path) continue; /* Android input (Bluetooth): cannot be handed over raw */
|
||||
Uint16 vid = SDL_GetGamepadVendorForID(ids[i]), pid = SDL_GetGamepadProductForID(ids[i]);
|
||||
if (hk_type_known(vid, pid)) continue;
|
||||
hk_log(env, "hookup: taking %04x:%04x \"%s\" from SDL's gamepad layer", vid, pid,
|
||||
SDL_GetGamepadNameForID(ids[i]) ? SDL_GetGamepadNameForID(ids[i]) : "?");
|
||||
hk_add_type(vid, pid, hk_path_iface(path));
|
||||
handed = true;
|
||||
}
|
||||
SDL_free(ids);
|
||||
if (handed) {
|
||||
hk_log(env, "hookup: restarting SDL's gamepad layer so it lets go (ignored: %s)", g_hk_types);
|
||||
hk_apply_ignore_list(env);
|
||||
restart_gamepads(env); /* SDL closes them; they stay ignored; the scan below opens them raw */
|
||||
g_hk_changes = 0xffffffffu;
|
||||
}
|
||||
}
|
||||
|
||||
static void hookup_scan(JNIEnv *env)
|
||||
{
|
||||
if (!g_hk_type_count) return;
|
||||
SDL_hid_device_info *list = SDL_hid_enumerate(0, 0);
|
||||
for (SDL_hid_device_info *d = list; d; d = d->next) {
|
||||
if (!d->path || !hk_type_known(d->vendor_id, d->product_id)) continue;
|
||||
int want = hk_type_iface(d->vendor_id, d->product_id);
|
||||
int iface = hk_path_iface(d->path);
|
||||
if (want >= 0 && iface != want) continue;
|
||||
if (d->bus_type == SDL_HID_API_BUS_BLUETOOTH) continue;
|
||||
if (!hk_path_open(d->path)) hk_log(env, "hookup: found %04x:%04x at %s, opening it raw", d->vendor_id, d->product_id, d->path);
|
||||
hk_open(env, d->path, d->vendor_id, d->product_id, iface);
|
||||
}
|
||||
SDL_hid_free_enumeration(list);
|
||||
}
|
||||
|
||||
static void hookup_run_queue(JNIEnv *env)
|
||||
{
|
||||
for (;;) {
|
||||
HookupReq r;
|
||||
SDL_LockSpinlock(&g_hk_lock);
|
||||
bool have = g_hk_head != g_hk_tail;
|
||||
if (have) { r = g_hk_queue[g_hk_head]; g_hk_head = (g_hk_head + 1) % HK_QUEUE; }
|
||||
SDL_UnlockSpinlock(&g_hk_lock);
|
||||
if (!have) return;
|
||||
SDL_hid_device *dev = g_hk[r.slot].dev;
|
||||
if (r.type == HK_GET_FEATURE || r.type == HK_GET_INPUT) {
|
||||
Uint8 buf[HOOKUP_REPORT_MAX + 1] = { 0 };
|
||||
int want = r.data[1] ? r.data[1] : HOOKUP_REPORT_MAX;
|
||||
buf[0] = r.data[0];
|
||||
int n = -1;
|
||||
if (dev) n = r.type == HK_GET_INPUT ? SDL_hid_get_input_report(dev, buf, (size_t)want)
|
||||
: SDL_hid_get_feature_report(dev, buf, (size_t)want);
|
||||
jbyteArray arr = n > 0 ? hk_bytes(env, buf, n) : NULL;
|
||||
if (g_hk_reply) (*env)->CallStaticVoidMethod(env, g_cls, g_hk_reply, (jint)r.slot, r.request, arr);
|
||||
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
|
||||
if (arr) (*env)->DeleteLocalRef(env, arr);
|
||||
} else if (dev && r.type == HK_FEATURE_SET) {
|
||||
SDL_hid_send_feature_report(dev, r.data, (size_t)r.len);
|
||||
} else if (dev && r.type == HK_OUT) {
|
||||
SDL_hid_write(dev, r.data, (size_t)r.len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Steam Controller (2026): cable 28de:1302, wireless puck 28de:1304/1305 (one controller per interface 2..5).
|
||||
* SDL's gamepad layer never opens it (it is always on the ignore list; outside hook-up, triton.h passes it
|
||||
* through to DroidDeck's own Steam Controller node), so hook-up finds it itself. Android doesn't say which of
|
||||
* its HID interfaces is the controller, so the candidates are opened and watched, and the one that carries a
|
||||
* controller -- state reports, or the puck announcing a connected controller -- is handed to Steam as itself,
|
||||
* exactly like on a PC (Steam drives lizard mode, haptics, trackpads, grip sense, IMU). Only interfaces with a
|
||||
* controller get a hook-up slot, so a puck doesn't use up all four.
|
||||
*/
|
||||
#define HK_WATCH_MAX 6
|
||||
typedef struct {
|
||||
SDL_hid_device *dev;
|
||||
char path[256];
|
||||
Uint16 pid;
|
||||
int iface;
|
||||
} HkWatch;
|
||||
static HkWatch g_hkw[HK_WATCH_MAX];
|
||||
static int g_hkw_full_logged;
|
||||
|
||||
static bool hk_triton_puck(Uint16 pid) { return pid == 0x1304 || pid == 0x1305; }
|
||||
|
||||
static bool hk_watching(const char *path)
|
||||
{
|
||||
for (int w = 0; w < HK_WATCH_MAX; w++) if (g_hkw[w].dev && !strcmp(g_hkw[w].path, path)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
static void hk_watch_close_all(void)
|
||||
{
|
||||
for (int w = 0; w < HK_WATCH_MAX; w++) {
|
||||
if (g_hkw[w].dev) SDL_hid_close(g_hkw[w].dev);
|
||||
memset(&g_hkw[w], 0, sizeof(g_hkw[w]));
|
||||
}
|
||||
}
|
||||
|
||||
static void hk_valve_scan(JNIEnv *env)
|
||||
{
|
||||
SDL_hid_device_info *list = SDL_hid_enumerate(VALVE_VID, 0);
|
||||
for (SDL_hid_device_info *d = list; d; d = d->next) {
|
||||
if (!d->path || !triton_pid(d->product_id)) continue;
|
||||
if (hk_triton_puck(d->product_id) && (d->interface_number < 2 || d->interface_number > 5)) continue;
|
||||
if (d->interface_class == 3 && d->interface_subclass == 1) continue; /* boot keyboard / mouse (lizard mode) */
|
||||
if (hk_path_open(d->path) || hk_watching(d->path)) continue;
|
||||
int w = -1;
|
||||
for (int k = 0; k < HK_WATCH_MAX; k++) if (!g_hkw[k].dev) { w = k; break; }
|
||||
if (w < 0) break;
|
||||
hk_prefetch(env, d->path); /* before it is opened: the descriptor can only be read while nobody holds it */
|
||||
SDL_hid_device *dev = SDL_hid_open_path(d->path);
|
||||
if (!dev) {
|
||||
hk_log(env, "hookup: could not open Steam Controller (2026) interface %d: %s", d->interface_number, SDL_GetError());
|
||||
continue;
|
||||
}
|
||||
SDL_hid_set_nonblocking(dev, 1);
|
||||
g_hkw[w].dev = dev;
|
||||
SDL_strlcpy(g_hkw[w].path, d->path, sizeof(g_hkw[w].path));
|
||||
g_hkw[w].pid = d->product_id;
|
||||
g_hkw[w].iface = d->interface_number;
|
||||
if (!hk_triton_puck(d->product_id)) tri_lizard_off(dev); /* no stray mouse input until Steam owns it */
|
||||
hk_log(env, "hookup: Steam Controller (2026) %s, interface %d: waiting for controller data",
|
||||
hk_triton_puck(d->product_id) ? "puck" : "cable", d->interface_number);
|
||||
}
|
||||
SDL_hid_free_enumeration(list);
|
||||
}
|
||||
|
||||
static void hk_valve_poll(JNIEnv *env)
|
||||
{
|
||||
for (int w = 0; w < HK_WATCH_MAX; w++) {
|
||||
for (int reads = 0; g_hkw[w].dev && reads < 16; reads++) {
|
||||
Uint8 buf[HOOKUP_REPORT_MAX];
|
||||
int n = SDL_hid_read(g_hkw[w].dev, buf, sizeof(buf));
|
||||
if (n == 0) break;
|
||||
if (n < 0) {
|
||||
hk_log(env, "hookup: Steam Controller (2026) interface %d gone", g_hkw[w].iface);
|
||||
SDL_hid_close(g_hkw[w].dev);
|
||||
memset(&g_hkw[w], 0, sizeof(g_hkw[w]));
|
||||
break;
|
||||
}
|
||||
Uint8 id = buf[0];
|
||||
bool controller = id == 0x42 || id == 0x45 || id == 0x47 || ((id == 0x79 || id == 0x46) && n >= 2 && buf[1] == 2);
|
||||
if (!controller) continue;
|
||||
int slot = hk_free_slot();
|
||||
if (slot < 0) {
|
||||
if (!g_hkw_full_logged) hk_log(env, "hookup: a Steam Controller (2026) is ready but all %d hook-up slots are in use", HOOKUP_SLOTS);
|
||||
g_hkw_full_logged = 1;
|
||||
break;
|
||||
}
|
||||
g_hkw_full_logged = 0;
|
||||
HkWatch h = g_hkw[w];
|
||||
memset(&g_hkw[w], 0, sizeof(g_hkw[w])); /* the handle moves to the hook-up slot */
|
||||
hk_log(env, "hookup: Steam Controller (2026) on %s interface %d goes to Steam natively",
|
||||
hk_triton_puck(h.pid) ? "the puck," : "the cable,", h.iface);
|
||||
hk_adopt(env, slot, h.dev, h.path, VALVE_VID, h.pid, h.iface);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Why triton.h must not pass a Steam Controller (2026) through right now (NULL: it may). Hook-up hands it to
|
||||
* Steam itself while on -- and until it has actually released it after being switched off, so the two never
|
||||
* hold the same interface. */
|
||||
static const char *hookup_triton_off_why(void)
|
||||
{
|
||||
return atomic_load(&g_hookup_on) || g_hookup_applied == 1 ? "handed to Steam natively (Steam Native Hook-up)" : NULL;
|
||||
}
|
||||
|
||||
static void hookup_poll(JNIEnv *env, Uint64 now, bool driver_off)
|
||||
{
|
||||
hk_java_init(env);
|
||||
int on = atomic_load(&g_hookup_on) && !driver_off;
|
||||
if (on != g_hookup_applied) {
|
||||
int was = g_hookup_applied;
|
||||
g_hookup_applied = on;
|
||||
hk_log(env, "hookup: Steam Native Hook-up %s", on ? "ON" : "OFF");
|
||||
if (on) g_hk_changes = 0xffffffffu; /* look for controllers (incl. a Steam Controller 2026) right away */
|
||||
if (!on && was == 1) {
|
||||
for (int i = 0; i < HOOKUP_SLOTS; i++) hk_close(env, i, "Steam Native Hook-up off");
|
||||
hk_watch_close_all();
|
||||
g_tri_changes = 0xffffffffu; /* triton.h takes a Steam Controller (2026) back at once */
|
||||
g_hk_types[0] = 0;
|
||||
g_hk_type_count = 0;
|
||||
hk_apply_ignore_list(env);
|
||||
restart_gamepads(env); /* SDL takes the controllers back as gamepads */
|
||||
}
|
||||
}
|
||||
if (!on) {
|
||||
hookup_run_queue(env); /* answer stale reads */
|
||||
return;
|
||||
}
|
||||
static Uint64 last_take;
|
||||
if (now - last_take > 250) { last_take = now; hookup_take_gamepads(env); }
|
||||
Uint32 changes = SDL_hid_device_change_count();
|
||||
if (changes != g_hk_changes || now - g_hk_scan_ms > 2000) {
|
||||
g_hk_changes = changes;
|
||||
g_hk_scan_ms = now;
|
||||
hookup_scan(env);
|
||||
hk_valve_scan(env);
|
||||
}
|
||||
hk_valve_poll(env);
|
||||
/* reports are read by hk_reader(); here: controllers it saw go away, and Steam's side of the fast path */
|
||||
for (int i = 0; i < HOOKUP_SLOTS; i++)
|
||||
if (g_hk[i].dev && atomic_load(&g_hk_gone[i])) hk_close(env, i, "unplugged");
|
||||
if (now - g_hk_alive_ms > 500) {
|
||||
g_hk_alive_ms = now;
|
||||
int dropped = 0;
|
||||
pthread_mutex_lock(&g_hk_io);
|
||||
if (g_hks.base && !hks_alive(&g_hks)) { hks_unmap(&g_hks); dropped = 1; }
|
||||
pthread_mutex_unlock(&g_hk_io);
|
||||
if (dropped) hk_log(env, "hookup: DroidDeck's session ended; fast path off until it hands over its new shared file");
|
||||
}
|
||||
hk_serve_fast(env);
|
||||
hookup_run_queue(env);
|
||||
}
|
||||
+637
@@ -0,0 +1,637 @@
|
||||
/*
|
||||
* SDL3 controller loop. Reads the first gamepad (DualSense, DualSense Edge, Xbox, Switch Pro, ... anything SDL3
|
||||
* supports) and pushes frames to Java (NativeBridge.onFrame). Rumble/lightbar requests come back through
|
||||
* NativeBridge.nativeSetOutput.
|
||||
*/
|
||||
#include <SDL3/SDL.h>
|
||||
#include <SDL3/SDL_main.h>
|
||||
#include <jni.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define FRAME_LEN 22
|
||||
#define MAX_PADS 4
|
||||
|
||||
static JavaVM *g_vm;
|
||||
static jclass g_cls;
|
||||
static jmethodID g_frame, g_status, g_gone, g_info, g_caps;
|
||||
|
||||
/* Per-slot output state, written from Java threads, read by the SDL thread. */
|
||||
static _Atomic int g_rl[MAX_PADS], g_rr[MAX_PADS];
|
||||
static _Atomic int g_rumble_dirty[MAX_PADS];
|
||||
static _Atomic int g_led_dirty[MAX_PADS];
|
||||
static _Atomic int g_led_r[MAX_PADS], g_led_g[MAX_PADS], g_led_b[MAX_PADS]; /* per-slot lightbar colour */
|
||||
static _Atomic int g_player_idx[MAX_PADS]; /* per-slot player LEDs: -1 = off, 0..3 = player 1..4 */
|
||||
static _Atomic int g_player_dirty[MAX_PADS];
|
||||
|
||||
JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved)
|
||||
{
|
||||
(void)reserved;
|
||||
JNIEnv *env;
|
||||
if ((*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) return JNI_ERR;
|
||||
jclass c = (*env)->FindClass(env, "com/example/dsedge/NativeBridge");
|
||||
if (!c) return JNI_ERR;
|
||||
g_cls = (jclass)(*env)->NewGlobalRef(env, c);
|
||||
g_frame = (*env)->GetStaticMethodID(env, g_cls, "onFrame", "([FI)V");
|
||||
g_status = (*env)->GetStaticMethodID(env, g_cls, "onStatus", "(Ljava/lang/String;)V");
|
||||
g_gone = (*env)->GetStaticMethodID(env, g_cls, "onPadGone", "(I)V");
|
||||
g_info = (*env)->GetStaticMethodID(env, g_cls, "onPadInfo", "(IIILjava/lang/String;)V");
|
||||
g_caps = (*env)->GetStaticMethodID(env, g_cls, "onPadCaps", "(IIIILjava/lang/String;)V");
|
||||
g_vm = vm;
|
||||
return JNI_VERSION_1_6;
|
||||
}
|
||||
|
||||
/* Slot 0: rumble + lightbar colour (the user's light settings). */
|
||||
JNIEXPORT void JNICALL Java_com_example_dsedge_NativeBridge_nativeSetLed(
|
||||
JNIEnv *env, jclass cls, jint slot, jint r, jint g, jint b)
|
||||
{
|
||||
(void)env; (void)cls;
|
||||
if (slot < 0 || slot >= MAX_PADS) return;
|
||||
atomic_store(&g_led_r[slot], r); atomic_store(&g_led_g[slot], g); atomic_store(&g_led_b[slot], b);
|
||||
atomic_store(&g_led_dirty[slot], 1);
|
||||
}
|
||||
|
||||
/* Rumble for any slot (0..3). */
|
||||
JNIEXPORT void JNICALL Java_com_example_dsedge_NativeBridge_nativeSetRumble(
|
||||
JNIEnv *env, jclass cls, jint slot, jint rl, jint rr)
|
||||
{
|
||||
(void)env; (void)cls;
|
||||
if (slot < 0 || slot >= MAX_PADS) return;
|
||||
atomic_store(&g_rl[slot], rl); atomic_store(&g_rr[slot], rr);
|
||||
atomic_store(&g_rumble_dirty[slot], 1);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_example_dsedge_NativeBridge_nativeSetPlayerLed(JNIEnv *env, jclass cls, jint slot, jint index)
|
||||
{
|
||||
(void)env; (void)cls;
|
||||
if (slot < 0 || slot >= MAX_PADS) return;
|
||||
atomic_store(&g_player_idx[slot], index);
|
||||
atomic_store(&g_player_dirty[slot], 1);
|
||||
}
|
||||
|
||||
static atomic_int g_force = 1; /* 1 = only accept pads served by SDL's own USB (HIDAPI) driver */
|
||||
static atomic_int g_rescan = 0;
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_example_dsedge_NativeBridge_nativeSetForce(JNIEnv *env, jclass c, jint on)
|
||||
{
|
||||
(void)env; (void)c;
|
||||
atomic_store(&g_force, on ? 1 : 0);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_example_dsedge_NativeBridge_nativeRescan(JNIEnv *env, jclass c)
|
||||
{
|
||||
(void)env; (void)c;
|
||||
atomic_store(&g_rescan, 1);
|
||||
}
|
||||
|
||||
static atomic_int g_driver_off = 0; /* 1 = SDL3 (HIDAPI) driver disabled: release the controller to Android */
|
||||
static atomic_int g_poll_ms = 2; /* loop period: 2ms = 500Hz (lower = lower latency, more CPU) */
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_example_dsedge_NativeBridge_nativeSetPollMs(JNIEnv *env, jclass c, jint ms)
|
||||
{
|
||||
(void)env; (void)c;
|
||||
if (ms < 1) ms = 1;
|
||||
if (ms > 16) ms = 16;
|
||||
atomic_store(&g_poll_ms, ms);
|
||||
}
|
||||
|
||||
/* Hard on/off for the SDL3 driver. Off disables HIDAPI and releases the controller; on re-enables it. */
|
||||
JNIEXPORT void JNICALL Java_com_example_dsedge_NativeBridge_nativeSetDriver(JNIEnv *env, jclass c, jint on)
|
||||
{
|
||||
(void)env; (void)c;
|
||||
atomic_store(&g_driver_off, on ? 0 : 1);
|
||||
SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI, on ? "1" : "0");
|
||||
atomic_store(&g_rescan, 1);
|
||||
}
|
||||
|
||||
/* A line in DroidDeck's session log ("sdl3bridge: ...") through NativeBridge.onBridgeLog. */
|
||||
static void engine_log(JNIEnv *env, const char *msg)
|
||||
{
|
||||
SDL_Log("%s", msg);
|
||||
jmethodID m = (*env)->GetStaticMethodID(env, g_cls, "onBridgeLog", "(Ljava/lang/String;)V");
|
||||
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); return; }
|
||||
jstring s = (*env)->NewStringUTF(env, msg);
|
||||
if (m && s) (*env)->CallStaticVoidMethod(env, g_cls, m, s);
|
||||
if (s) (*env)->DeleteLocalRef(env, s);
|
||||
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
|
||||
}
|
||||
|
||||
static void send_status(JNIEnv *env, const char *msg)
|
||||
{
|
||||
jstring s = (*env)->NewStringUTF(env, msg);
|
||||
(*env)->CallStaticVoidMethod(env, g_cls, g_status, s);
|
||||
(*env)->DeleteLocalRef(env, s);
|
||||
}
|
||||
|
||||
static void send_gone(JNIEnv *env, int slot)
|
||||
{
|
||||
(*env)->CallStaticVoidMethod(env, g_cls, g_gone, (jint)slot);
|
||||
}
|
||||
|
||||
static void send_info(JNIEnv *env, int slot, int vid, int pid, const char *name)
|
||||
{
|
||||
jstring s = (*env)->NewStringUTF(env, name ? name : "gamepad");
|
||||
(*env)->CallStaticVoidMethod(env, g_cls, g_info, (jint)slot, (jint)vid, (jint)pid, s);
|
||||
(*env)->DeleteLocalRef(env, s);
|
||||
}
|
||||
|
||||
#include "triton.h"
|
||||
#include "hookup.h"
|
||||
|
||||
/* SDL button -> bit in the frame mask. Bit layout is shared with the first bridge and DroidDeck's client. */
|
||||
static const struct { SDL_GamepadButton button; int bit; } BUTTONS[] = {
|
||||
{ SDL_GAMEPAD_BUTTON_SOUTH, 0 }, /* Cross */
|
||||
{ SDL_GAMEPAD_BUTTON_EAST, 1 }, /* Circle */
|
||||
{ SDL_GAMEPAD_BUTTON_WEST, 2 }, /* Square */
|
||||
{ SDL_GAMEPAD_BUTTON_NORTH, 3 }, /* Triangle */
|
||||
{ SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, 4 },
|
||||
{ SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, 5 },
|
||||
{ SDL_GAMEPAD_BUTTON_BACK, 8 }, /* Create */
|
||||
{ SDL_GAMEPAD_BUTTON_START, 9 }, /* Options */
|
||||
{ SDL_GAMEPAD_BUTTON_LEFT_STICK, 10 },
|
||||
{ SDL_GAMEPAD_BUTTON_RIGHT_STICK, 11 },
|
||||
{ SDL_GAMEPAD_BUTTON_GUIDE, 12 }, /* PS */
|
||||
{ SDL_GAMEPAD_BUTTON_TOUCHPAD, 13 },
|
||||
{ SDL_GAMEPAD_BUTTON_MISC1, 14 }, /* Mute */
|
||||
{ SDL_GAMEPAD_BUTTON_DPAD_UP, 15 },
|
||||
{ SDL_GAMEPAD_BUTTON_DPAD_DOWN, 16 },
|
||||
{ SDL_GAMEPAD_BUTTON_DPAD_LEFT, 17 },
|
||||
{ SDL_GAMEPAD_BUTTON_DPAD_RIGHT, 18 },
|
||||
{ SDL_GAMEPAD_BUTTON_LEFT_PADDLE1, 19 }, /* Edge left back button */
|
||||
{ SDL_GAMEPAD_BUTTON_RIGHT_PADDLE1, 20 }, /* Edge right back button */
|
||||
{ SDL_GAMEPAD_BUTTON_LEFT_PADDLE2, 21 }, /* Edge left Fn */
|
||||
{ SDL_GAMEPAD_BUTTON_RIGHT_PADDLE2, 22 }, /* Edge right Fn */
|
||||
};
|
||||
|
||||
/* Extra buttons that don't fit the 0..22 mask safely in a float -> a second mask in f[21]. */
|
||||
static const struct { SDL_GamepadButton button; int bit; } BUTTONS2[] = {
|
||||
{ SDL_GAMEPAD_BUTTON_MISC2, 0 }, /* e.g. Flydigi C */
|
||||
{ SDL_GAMEPAD_BUTTON_MISC3, 1 }, /* e.g. Flydigi Z */
|
||||
{ SDL_GAMEPAD_BUTTON_MISC4, 2 },
|
||||
{ SDL_GAMEPAD_BUTTON_MISC5, 3 },
|
||||
{ SDL_GAMEPAD_BUTTON_MISC6, 4 },
|
||||
};
|
||||
|
||||
static float stick(Sint16 v) { return (float)(((int)v + 32768) >> 8); } /* 0..255, 128 = centre */
|
||||
static float trigger(Sint16 v) { return (float)((int)v * 255 / 32767); } /* 0..255 */
|
||||
|
||||
static void send_frame(JNIEnv *env, int slot, SDL_Gamepad *pad, jfloatArray arr)
|
||||
{
|
||||
float f[FRAME_LEN];
|
||||
memset(f, 0, sizeof(f));
|
||||
|
||||
int mask = 0;
|
||||
for (size_t i = 0; i < SDL_arraysize(BUTTONS); i++) {
|
||||
if (SDL_GetGamepadButton(pad, BUTTONS[i].button)) mask |= 1 << BUTTONS[i].bit;
|
||||
}
|
||||
f[1] = stick(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFTX));
|
||||
f[2] = stick(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFTY));
|
||||
f[3] = stick(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHTX));
|
||||
f[4] = stick(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHTY));
|
||||
f[5] = trigger(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFT_TRIGGER));
|
||||
f[6] = trigger(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER));
|
||||
if (f[5] > 30.0f) mask |= 1 << 6;
|
||||
if (f[6] > 30.0f) mask |= 1 << 7;
|
||||
f[0] = (float)mask; /* < 2^24, exact in a float */
|
||||
int mask2 = 0;
|
||||
for (size_t i = 0; i < SDL_arraysize(BUTTONS2); i++) {
|
||||
if (SDL_GetGamepadButton(pad, BUTTONS2[i].button)) mask2 |= 1 << BUTTONS2[i].bit;
|
||||
}
|
||||
f[21] = (float)mask2;
|
||||
|
||||
float v[3];
|
||||
if (SDL_GetGamepadSensorData(pad, SDL_SENSOR_GYRO, v, 3)) { f[7] = v[0]; f[8] = v[1]; f[9] = v[2]; }
|
||||
if (SDL_GetGamepadSensorData(pad, SDL_SENSOR_ACCEL, v, 3)) { f[10] = v[0]; f[11] = v[1]; f[12] = v[2]; }
|
||||
|
||||
int ntp = SDL_GetNumGamepadTouchpads(pad);
|
||||
if (ntp >= 2) {
|
||||
/* two trackpads (e.g. Steam Controller): finger slot 0 = pad 0, slot 1 = pad 1 */
|
||||
for (int tp = 0; tp < 2; tp++) {
|
||||
bool down = false; float x = 0, y = 0, p = 0;
|
||||
if (SDL_GetGamepadTouchpadFinger(pad, tp, 0, &down, &x, &y, &p) && down) {
|
||||
f[13 + 3 * tp] = 1.0f;
|
||||
f[14 + 3 * tp] = x * 1919.0f;
|
||||
f[15 + 3 * tp] = y * 1079.0f;
|
||||
}
|
||||
}
|
||||
} else if (ntp == 1) {
|
||||
for (int i = 0; i < 2; i++) {
|
||||
bool down = false;
|
||||
float x = 0, y = 0, p = 0;
|
||||
if (SDL_GetGamepadTouchpadFinger(pad, 0, i, &down, &x, &y, &p) && down) {
|
||||
f[13 + 3 * i] = 1.0f;
|
||||
f[14 + 3 * i] = x * 1919.0f; /* normalized; the view divides by the same */
|
||||
f[15 + 3 * i] = y * 1079.0f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int pct = -1;
|
||||
SDL_PowerState ps = SDL_GetGamepadPowerInfo(pad, &pct);
|
||||
f[19] = (float)pct;
|
||||
f[20] = (float)ps;
|
||||
|
||||
(*env)->SetFloatArrayRegion(env, arr, 0, FRAME_LEN, f);
|
||||
(*env)->CallStaticVoidMethod(env, g_cls, g_frame, arr, (jint)slot);
|
||||
}
|
||||
|
||||
/* SDL's own USB driver gives the gamepad a device path; Android's basic input path does not.
|
||||
* Only the USB driver provides gyro, touchpad and the Edge back buttons. */
|
||||
static bool pad_is_full_driver(SDL_Gamepad *pad) { return SDL_GetGamepadPath(pad) != NULL; }
|
||||
|
||||
static void enable_sensors(SDL_Gamepad *pad)
|
||||
{
|
||||
static const SDL_SensorType types[] = { SDL_SENSOR_GYRO, SDL_SENSOR_ACCEL };
|
||||
for (size_t i = 0; i < SDL_arraysize(types); i++) {
|
||||
if (SDL_GamepadHasSensor(pad, types[i]) && !SDL_GamepadSensorEnabled(pad, types[i])) {
|
||||
SDL_SetGamepadSensorEnabled(pad, types[i], true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void describe(SDL_Gamepad *pad, char *buf, size_t n)
|
||||
{
|
||||
const char *name = SDL_GetGamepadName(pad);
|
||||
SDL_JoystickConnectionState cs = SDL_GetGamepadConnectionState(pad);
|
||||
snprintf(buf, n, "Connected: %s [%s] vid=%04x pid=%04x %s | gyro:%s accel:%s touchpads:%d",
|
||||
name ? name : "gamepad",
|
||||
pad_is_full_driver(pad) ? "SDL3 USB driver: full features"
|
||||
: "Android input (e.g. Bluetooth): SDL3's own driver can't reach it, some extras may be missing",
|
||||
(unsigned)SDL_GetGamepadVendor(pad), (unsigned)SDL_GetGamepadProduct(pad),
|
||||
cs == SDL_JOYSTICK_CONNECTION_WIRED ? "wired" : (cs == SDL_JOYSTICK_CONNECTION_WIRELESS ? "wireless" : "link unknown"),
|
||||
SDL_GamepadHasSensor(pad, SDL_SENSOR_GYRO) ? "yes" : "no",
|
||||
SDL_GamepadHasSensor(pad, SDL_SENSOR_ACCEL) ? "yes" : "no",
|
||||
SDL_GetNumGamepadTouchpads(pad));
|
||||
|
||||
/* Every gamepad SDL knows about, so we can tell if the USB-driver version of the controller exists. */
|
||||
int cnt = 0;
|
||||
SDL_JoystickID *ids = SDL_GetGamepads(&cnt);
|
||||
SDL_strlcat(buf, " | SDL sees:", n);
|
||||
for (int i = 0; ids && i < cnt; i++) {
|
||||
const char *nm = SDL_GetGamepadNameForID(ids[i]);
|
||||
char one[120];
|
||||
snprintf(one, sizeof(one), " [%s: %s]", SDL_GetGamepadPathForID(ids[i]) ? "usb driver" : "android", nm ? nm : "?");
|
||||
SDL_strlcat(buf, one, n);
|
||||
}
|
||||
if (cnt == 0) SDL_strlcat(buf, " nothing", n);
|
||||
SDL_free(ids);
|
||||
}
|
||||
|
||||
static char g_last_diag[512];
|
||||
|
||||
/* In forced mode an Android-path gamepad (no SDL USB path) is never used. */
|
||||
static bool usable_id(SDL_JoystickID id)
|
||||
{
|
||||
/* A Steam Controller (2026) is never a bridge player: it is passed through raw (see triton.h). */
|
||||
if (SDL_GetGamepadVendorForID(id) == VALVE_VID && triton_pid(SDL_GetGamepadProductForID(id))) return false;
|
||||
return !atomic_load(&g_force) || SDL_GetGamepadPathForID(id) != NULL;
|
||||
}
|
||||
|
||||
/* The same physical controller can show up twice: once through SDL's USB driver and once through Android's basic
|
||||
* input. The Android copy is a duplicate and is never used as its own player. */
|
||||
static bool android_duplicate(SDL_JoystickID id)
|
||||
{
|
||||
if (SDL_GetGamepadPathForID(id) != NULL) return false;
|
||||
Uint16 vid = SDL_GetGamepadVendorForID(id), pid = SDL_GetGamepadProductForID(id);
|
||||
int cnt = 0, full = 0, rank = 0;
|
||||
bool seen = false;
|
||||
SDL_JoystickID *ids = SDL_GetGamepads(&cnt);
|
||||
for (int i = 0; ids && i < cnt; i++) {
|
||||
if (SDL_GetGamepadVendorForID(ids[i]) != vid || SDL_GetGamepadProductForID(ids[i]) != pid) continue;
|
||||
if (SDL_GetGamepadPathForID(ids[i]) != NULL) { full++; continue; }
|
||||
if (ids[i] == id) seen = true;
|
||||
else if (!seen) rank++;
|
||||
}
|
||||
SDL_free(ids);
|
||||
return rank < full;
|
||||
}
|
||||
|
||||
static SDL_Gamepad *g_pads[MAX_PADS];
|
||||
static SDL_JoystickID g_ids[MAX_PADS];
|
||||
|
||||
static int rumble_on[MAX_PADS];
|
||||
|
||||
static int pad_count(void)
|
||||
{
|
||||
int n = 0;
|
||||
for (int i = 0; i < MAX_PADS; i++) if (g_pads[i]) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
static int slot_of(SDL_JoystickID id)
|
||||
{
|
||||
for (int i = 0; i < MAX_PADS; i++) if (g_pads[i] && g_ids[i] == id) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static void refresh_status(JNIEnv *env)
|
||||
{
|
||||
char diag[560];
|
||||
if (atomic_load(&g_driver_off)) {
|
||||
snprintf(diag, sizeof(diag), "SDL3 driver OFF \u2014 controller released to Android (tap the bubble to turn it back on)");
|
||||
} else if (g_pads[0]) {
|
||||
describe(g_pads[0], diag, sizeof(diag));
|
||||
char tail[80];
|
||||
snprintf(tail, sizeof(tail), " | players:%d%s", pad_count(),
|
||||
triton_active() ? " | + Steam Controller (2026) raw passthrough" : "");
|
||||
SDL_strlcat(diag, tail, sizeof(diag));
|
||||
if (hookup_active()) {
|
||||
snprintf(tail, sizeof(tail), " | + %d controller(s) handed to Steam natively%s", hookup_count(),
|
||||
hookup_fast_count() ? " (fast path)" : "");
|
||||
SDL_strlcat(diag, tail, sizeof(diag));
|
||||
} else if (atomic_load(&g_hookup_held)) {
|
||||
SDL_strlcat(diag, " | Steam Native Hook-up waits for Steam on DroidDeck's desktop", sizeof(diag));
|
||||
}
|
||||
} else if (hookup_active()) {
|
||||
snprintf(diag, sizeof(diag), "Connected: Steam Native Hook-up | %d controller(s) handed to Steam as the real "
|
||||
"device (Steam's own driver: all buttons, touchpads, gyro, rumble, lights)%s%s", hookup_count(),
|
||||
hookup_fast_count() ? " | fast path: shared memory" : "",
|
||||
triton_active() ? " | + Steam Controller (2026) raw passthrough" : "");
|
||||
} else if (triton_active()) {
|
||||
snprintf(diag, sizeof(diag), "Connected: %s | raw passthrough to DroidDeck (all sensors, capacitive "
|
||||
"touch, grip sense, trackpad pressure and haptics handled by Steam)", tri_kind(&g_tri[g_tri_active]));
|
||||
} else {
|
||||
int cnt = 0, ignored = 0;
|
||||
SDL_JoystickID *ids = SDL_GetGamepads(&cnt);
|
||||
for (int i = 0; ids && i < cnt; i++) if (!usable_id(ids[i])) ignored++;
|
||||
SDL_free(ids);
|
||||
snprintf(diag, sizeof(diag),
|
||||
"Forced SDL3 USB mode: waiting for the USB driver. Plug the controller in with a USB-C cable, "
|
||||
"then tap 'Force SDL3 USB driver' and allow USB access (or switch Controller source to Auto to "
|
||||
"also use Bluetooth / Android-only controllers). Ignored Android-only controllers: %d", ignored);
|
||||
if (!atomic_load(&g_force))
|
||||
snprintf(diag, sizeof(diag), "Waiting for a controller: plug any SDL3-supported controller in via USB-C "
|
||||
"(full features) or connect it over Bluetooth");
|
||||
}
|
||||
if (strcmp(diag, g_last_diag) != 0) {
|
||||
SDL_strlcpy(g_last_diag, diag, sizeof(g_last_diag));
|
||||
send_status(env, diag);
|
||||
}
|
||||
}
|
||||
|
||||
/* Which buttons/axes/touchpads this controller actually has, so the UI can draw a universal layout. */
|
||||
static void send_caps(JNIEnv *env, int slot, SDL_Gamepad *pad)
|
||||
{
|
||||
int present = 0;
|
||||
for (size_t i = 0; i < SDL_arraysize(BUTTONS); i++) {
|
||||
if (SDL_GamepadHasButton(pad, BUTTONS[i].button)) present |= 1 << BUTTONS[i].bit;
|
||||
}
|
||||
int axes = 0;
|
||||
if (SDL_GamepadHasAxis(pad, SDL_GAMEPAD_AXIS_LEFTX)) axes |= 1;
|
||||
if (SDL_GamepadHasAxis(pad, SDL_GAMEPAD_AXIS_RIGHTX)) axes |= 2;
|
||||
if (SDL_GamepadHasAxis(pad, SDL_GAMEPAD_AXIS_LEFT_TRIGGER)) axes |= 4;
|
||||
if (SDL_GamepadHasAxis(pad, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER)) axes |= 8;
|
||||
int touchpads = SDL_GetNumGamepadTouchpads(pad);
|
||||
|
||||
const char *kind;
|
||||
switch (SDL_GetGamepadType(pad)) {
|
||||
case SDL_GAMEPAD_TYPE_PS3:
|
||||
case SDL_GAMEPAD_TYPE_PS4:
|
||||
case SDL_GAMEPAD_TYPE_PS5: kind = "ps"; break;
|
||||
case SDL_GAMEPAD_TYPE_XBOX360:
|
||||
case SDL_GAMEPAD_TYPE_XBOXONE: kind = "xbox"; break;
|
||||
case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO:
|
||||
case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT:
|
||||
case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT:
|
||||
case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_PAIR: kind = "nintendo"; break;
|
||||
case SDL_GAMEPAD_TYPE_STEAM: kind = "steam"; break;
|
||||
default: {
|
||||
const char *nm = SDL_GetGamepadName(pad);
|
||||
kind = (nm && SDL_strcasestr(nm, "steam")) ? "steam" : "generic";
|
||||
}
|
||||
}
|
||||
jstring k = (*env)->NewStringUTF(env, kind);
|
||||
(*env)->CallStaticVoidMethod(env, g_cls, g_caps, (jint)slot, (jint)present, (jint)axes, (jint)touchpads, k);
|
||||
(*env)->DeleteLocalRef(env, k);
|
||||
}
|
||||
|
||||
static void setup_slot(JNIEnv *env, int slot)
|
||||
{
|
||||
SDL_Gamepad *pad = g_pads[slot];
|
||||
enable_sensors(pad);
|
||||
atomic_store(&g_led_dirty[slot], 1);
|
||||
atomic_store(&g_rumble_dirty[slot], 1);
|
||||
atomic_store(&g_player_dirty[slot], 1);
|
||||
send_info(env, slot, SDL_GetGamepadVendor(pad), SDL_GetGamepadProduct(pad), SDL_GetGamepadName(pad));
|
||||
send_caps(env, slot, pad);
|
||||
g_last_diag[0] = 0;
|
||||
}
|
||||
|
||||
static void open_unopened(JNIEnv *env)
|
||||
{
|
||||
if (atomic_load(&g_driver_off)) return; /* driver off: don't claim anything */
|
||||
int n = 0;
|
||||
SDL_JoystickID *ids = SDL_GetGamepads(&n);
|
||||
for (int i = 0; ids && i < n; i++) {
|
||||
if (slot_of(ids[i]) >= 0 || !usable_id(ids[i]) || android_duplicate(ids[i])) continue;
|
||||
int free_slot = -1;
|
||||
for (int s = 0; s < MAX_PADS; s++) if (!g_pads[s]) { free_slot = s; break; }
|
||||
if (free_slot < 0) break;
|
||||
SDL_Gamepad *p = SDL_OpenGamepad(ids[i]);
|
||||
if (!p) continue;
|
||||
g_pads[free_slot] = p;
|
||||
g_ids[free_slot] = ids[i];
|
||||
setup_slot(env, free_slot);
|
||||
}
|
||||
SDL_free(ids);
|
||||
}
|
||||
|
||||
/* Closes a slot. If it was player 1, the next controller moves up so DroidDeck's primary pad is never empty. */
|
||||
static void close_slot(JNIEnv *env, int slot)
|
||||
{
|
||||
if (!g_pads[slot]) return;
|
||||
SDL_RumbleGamepad(g_pads[slot], 0, 0, 0);
|
||||
SDL_CloseGamepad(g_pads[slot]);
|
||||
g_pads[slot] = NULL;
|
||||
atomic_store(&g_rl[slot], 0);
|
||||
atomic_store(&g_rr[slot], 0);
|
||||
send_gone(env, slot);
|
||||
if (slot == 0) {
|
||||
for (int k = 1; k < MAX_PADS; k++) {
|
||||
if (!g_pads[k]) continue;
|
||||
g_pads[0] = g_pads[k];
|
||||
g_ids[0] = g_ids[k];
|
||||
g_pads[k] = NULL;
|
||||
send_gone(env, k);
|
||||
setup_slot(env, 0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
g_last_diag[0] = 0;
|
||||
}
|
||||
|
||||
/* Drops controllers that are no longer usable (forced mode switched on, or an Android duplicate of a USB-driver pad). */
|
||||
static void drop_unusable(JNIEnv *env)
|
||||
{
|
||||
for (int s = 0; s < MAX_PADS; s++) {
|
||||
if (!g_pads[s]) continue;
|
||||
if (!usable_id(g_ids[s]) || android_duplicate(g_ids[s])) { rumble_on[s] = 0; close_slot(env, s); }
|
||||
}
|
||||
}
|
||||
|
||||
/* Close every bridge player and restart SDL's gamepad layer (re-enumerates; ignore hints take effect).
|
||||
* Raw handles (Steam Controller passthrough, Steam Native Hook-up) survive: main() holds an SDL_hid_init
|
||||
* reference so the HID layer itself stays up. */
|
||||
static void restart_gamepads(JNIEnv *env)
|
||||
{
|
||||
for (int s = 0; s < MAX_PADS; s++) {
|
||||
if (g_pads[s]) { SDL_CloseGamepad(g_pads[s]); g_pads[s] = NULL; send_gone(env, s); }
|
||||
rumble_on[s] = 0;
|
||||
}
|
||||
SDL_QuitSubSystem(SDL_INIT_GAMEPAD);
|
||||
SDL_InitSubSystem(SDL_INIT_GAMEPAD);
|
||||
g_last_diag[0] = 0;
|
||||
}
|
||||
|
||||
/* SDL only reports a joystick as a gamepad when it has a mapping. SDL ships mappings for thousands of
|
||||
* controllers and Android generates one for every Android gamepad, but a rare generic one (arcade stick,
|
||||
* cheap USB pad) may have none -- give it a sensible default layout so it still works as a player. */
|
||||
static void map_unmapped_joystick(SDL_JoystickID id)
|
||||
{
|
||||
if (SDL_IsGamepad(id)) return;
|
||||
SDL_Joystick *joy = SDL_OpenJoystick(id);
|
||||
if (!joy) return;
|
||||
int nb = SDL_GetNumJoystickButtons(joy), na = SDL_GetNumJoystickAxes(joy), nh = SDL_GetNumJoystickHats(joy);
|
||||
char guid[64], map[1024];
|
||||
SDL_GUIDToString(SDL_GetJoystickGUID(joy), guid, sizeof(guid));
|
||||
const char *name = SDL_GetJoystickName(joy);
|
||||
char clean[128];
|
||||
SDL_strlcpy(clean, name ? name : "Generic controller", sizeof(clean));
|
||||
for (char *c = clean; *c; c++) if (*c == ',') *c = ' ';
|
||||
SDL_CloseJoystick(joy);
|
||||
if (nb == 0 && na == 0) return;
|
||||
snprintf(map, sizeof(map), "%s,%s,", guid, clean);
|
||||
static const char *btn[] = { "a", "b", "x", "y", "leftshoulder", "rightshoulder", "back", "start",
|
||||
"leftstick", "rightstick", "guide", "lefttrigger", "righttrigger" };
|
||||
char one[48];
|
||||
int first_trigger_button = na >= 6 ? 11 : 13; /* analog triggers when there are 6+ axes */
|
||||
for (int b = 0; b < nb && b < (int)SDL_arraysize(btn); b++) {
|
||||
if (b >= first_trigger_button) break;
|
||||
snprintf(one, sizeof(one), "%s:b%d,", btn[b], b);
|
||||
SDL_strlcat(map, one, sizeof(map));
|
||||
}
|
||||
if (na < 6) {
|
||||
for (int b = 11; b < nb && b < 13; b++) {
|
||||
snprintf(one, sizeof(one), "%s:b%d,", btn[b], b);
|
||||
SDL_strlcat(map, one, sizeof(map));
|
||||
}
|
||||
}
|
||||
static const char *ax[] = { "leftx", "lefty", "rightx", "righty", "lefttrigger", "righttrigger" };
|
||||
for (int a = 0; a < na && a < 6; a++) {
|
||||
snprintf(one, sizeof(one), "%s:a%d,", ax[a], a);
|
||||
SDL_strlcat(map, one, sizeof(map));
|
||||
}
|
||||
if (nh > 0) SDL_strlcat(map, "dpup:h0.1,dpright:h0.2,dpdown:h0.4,dpleft:h0.8,", sizeof(map));
|
||||
if (SDL_AddGamepadMapping(map) >= 0) SDL_Log("bridge: default mapping for unmapped \"%s\": %s", clean, map);
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
/* argv[1]: SDL3's gamepad mappings file (absolute path, made by the app). Without it SDL3 looks the file up
|
||||
* through the app screen's assets -- headless there is no screen, and that lookup crashes the app. */
|
||||
if (argc > 1 && argv[1] && argv[1][0] == '/') SDL_SetHint(SDL_HINT_GAMECONTROLLERCONFIG_FILE, argv[1]);
|
||||
SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");
|
||||
SDL_SetHint(SDL_HINT_JOYSTICK_ENHANCED_REPORTS, "1");
|
||||
SDL_SetHint(SDL_HINT_ANDROID_BLOCK_ON_PAUSE, "0");
|
||||
SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI, "1");
|
||||
SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS5, "1");
|
||||
SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS4, "1");
|
||||
SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS5_PLAYER_LED, "1");
|
||||
/* Every SDL3 USB (HIDAPI) driver on, including Valve's (Steam Controller 2015 cable/dongle; it is off by
|
||||
* default in SDL). Only the Steam Controller (2026) is kept away from SDL's gamepad layer: it is passed
|
||||
* through raw instead (triton.h). That hint hides it from gamepads but not from SDL_hid_enumerate. */
|
||||
SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_STEAM, "1");
|
||||
SDL_SetHint(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES, "0x28de/0x1302,0x28de/0x1304,0x28de/0x1305");
|
||||
|
||||
JNIEnv *env = (JNIEnv *)SDL_GetAndroidJNIEnv();
|
||||
if (!env || !g_cls) {
|
||||
SDL_Log("SDL3Bridge: no JNI environment (%p) or bridge class (%p); SDL3's loop cannot run", (void *)env, (void *)g_cls);
|
||||
return 1;
|
||||
}
|
||||
engine_log(env, "engine: SDL3's loop started; initialising SDL3's gamepad support");
|
||||
|
||||
if (!SDL_Init(SDL_INIT_GAMEPAD)) {
|
||||
char msg[200];
|
||||
snprintf(msg, sizeof(msg), "SDL init failed: %s", SDL_GetError());
|
||||
send_status(env, msg);
|
||||
return 1;
|
||||
}
|
||||
engine_log(env, "engine: SDL3's gamepad support is up");
|
||||
SDL_hid_init(); /* keeps the HID layer alive across gamepad-layer restarts (raw passthrough handles) */
|
||||
send_status(env, "Waiting for a controller (plug it in via USB-C)");
|
||||
|
||||
jfloatArray arr = (*env)->NewFloatArray(env, FRAME_LEN);
|
||||
Uint64 last_scan = 0, last_tick = 0, last_rumble[MAX_PADS] = {0};
|
||||
|
||||
for (;;) {
|
||||
SDL_Event e;
|
||||
while (SDL_PollEvent(&e)) {
|
||||
if (e.type == SDL_EVENT_JOYSTICK_ADDED) {
|
||||
map_unmapped_joystick(e.jdevice.which);
|
||||
} else if (e.type == SDL_EVENT_GAMEPAD_ADDED) {
|
||||
drop_unusable(env);
|
||||
open_unopened(env);
|
||||
} else if (e.type == SDL_EVENT_GAMEPAD_REMOVED) {
|
||||
int s = slot_of(e.gdevice.which);
|
||||
if (s >= 0) {
|
||||
rumble_on[s] = 0;
|
||||
close_slot(env, s);
|
||||
if (pad_count() == 0) send_status(env, "Controller disconnected");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Uint64 now = SDL_GetTicks();
|
||||
|
||||
if (atomic_exchange(&g_rescan, 0)) { /* restart SDL's gamepad/HIDAPI enumeration */
|
||||
tri_close_all(env, "rescan");
|
||||
restart_gamepads(env);
|
||||
send_status(env, "Rescanning controllers...");
|
||||
}
|
||||
|
||||
if (now - last_scan > 1000) { /* fallback in case an ADDED event was missed, and housekeeping */
|
||||
last_scan = now;
|
||||
drop_unusable(env);
|
||||
open_unopened(env);
|
||||
}
|
||||
|
||||
if (now - last_tick > 1000) {
|
||||
last_tick = now;
|
||||
for (int s = 0; s < MAX_PADS; s++) if (g_pads[s]) enable_sensors(g_pads[s]);
|
||||
refresh_status(env);
|
||||
}
|
||||
|
||||
triton_poll(env, now, atomic_load(&g_driver_off) ? "SDL3 driver off" : hookup_triton_off_why());
|
||||
hookup_poll(env, now, atomic_load(&g_driver_off) != 0);
|
||||
|
||||
if (pad_count() > 0) SDL_UpdateGamepads();
|
||||
|
||||
for (int s = 0; s < MAX_PADS; s++) {
|
||||
SDL_Gamepad *pad = g_pads[s];
|
||||
if (!pad) continue;
|
||||
|
||||
if (atomic_exchange(&g_led_dirty[s], 0))
|
||||
SDL_SetGamepadLED(pad, (Uint8)atomic_load(&g_led_r[s]), (Uint8)atomic_load(&g_led_g[s]), (Uint8)atomic_load(&g_led_b[s]));
|
||||
if (atomic_exchange(&g_player_dirty[s], 0)) SDL_SetGamepadPlayerIndex(pad, atomic_load(&g_player_idx[s]));
|
||||
|
||||
int rl = atomic_load(&g_rl[s]), rr = atomic_load(&g_rr[s]);
|
||||
int rdirty = atomic_exchange(&g_rumble_dirty[s], 0);
|
||||
if (rl || rr) {
|
||||
if (rdirty || now - last_rumble[s] > 400) { /* SDL rumble has a duration, so refresh it */
|
||||
SDL_RumbleGamepad(pad, (Uint16)(rl * 257), (Uint16)(rr * 257), 1000);
|
||||
last_rumble[s] = now;
|
||||
}
|
||||
rumble_on[s] = 1;
|
||||
} else if (rumble_on[s]) {
|
||||
SDL_RumbleGamepad(pad, 0, 0, 0);
|
||||
rumble_on[s] = 0;
|
||||
}
|
||||
|
||||
send_frame(env, s, pad, arr);
|
||||
}
|
||||
SDL_Delay((Uint32)atomic_load(&g_poll_ms));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
/*
|
||||
* Steam Controller (2026, "Triton") raw passthrough over USB: the wired controller (28de:1302) or its
|
||||
* wireless "puck" dongle (28de:1304 / 28de:1305, one controller per HID interface 2..5).
|
||||
*
|
||||
* Nothing is decoded here. Every state report (buttons, sticks, trackpads with pressure, capacitive stick
|
||||
* touch, grip sense, IMU) goes to DroidDeck byte for byte, and everything Steam sends back (haptics,
|
||||
* settings, feature reads) goes to the controller unchanged, so Steam drives it exactly like a real one --
|
||||
* just over a cable/2.4 GHz link instead of Bluetooth LE.
|
||||
*
|
||||
* Included once, from main.c (uses its JNI globals). All SDL_hid calls run on the SDL thread.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#define VALVE_VID 0x28de
|
||||
#define TRITON_MAX_IFACES 4
|
||||
#define TRITON_REPORT_BYTES 64
|
||||
#define TRITON_STATE_PAYLOAD 45 /* bytes after the report id, as the Bluetooth descriptor declares */
|
||||
#define TRITON_LIZARD_REFRESH_MS 3000
|
||||
#define TRITON_RUMBLE_RESEND_MS 40
|
||||
|
||||
static bool triton_pid(Uint16 pid) { return pid == 0x1302 || pid == 0x1304 || pid == 0x1305; }
|
||||
static bool triton_dongle(Uint16 pid) { return pid == 0x1304 || pid == 0x1305; }
|
||||
|
||||
typedef struct {
|
||||
SDL_hid_device *dev;
|
||||
char path[256];
|
||||
int iface;
|
||||
Uint16 pid;
|
||||
} TritonIface;
|
||||
|
||||
static TritonIface g_tri[TRITON_MAX_IFACES];
|
||||
static int g_tri_active = -1; /* index in g_tri of the controller being passed through */
|
||||
static Uint32 g_tri_changes = 0xffffffffu;
|
||||
static Uint64 g_tri_scan_ms, g_tri_lizard_ms, g_tri_rumble_ms;
|
||||
static jmethodID g_tri_state, g_tri_conn, g_tri_feature;
|
||||
|
||||
/* ---- requests from Java (any thread) -> SDL thread ---- */
|
||||
enum { TRI_REQ_OUTPUT = 1, TRI_REQ_FEATURE_SET = 2, TRI_REQ_FEATURE_GET = 3 };
|
||||
typedef struct {
|
||||
int type;
|
||||
int len;
|
||||
jlong request;
|
||||
Uint8 data[TRITON_REPORT_BYTES + 1];
|
||||
} TritonReq;
|
||||
#define TRI_QUEUE 64
|
||||
static TritonReq g_tri_queue[TRI_QUEUE];
|
||||
static int g_tri_head, g_tri_tail;
|
||||
static SDL_SpinLock g_tri_lock; /* no init needed: Java may queue before the SDL thread starts */
|
||||
static _Atomic int g_tri_rl, g_tri_rr, g_tri_rumble_dirty;
|
||||
|
||||
static void tri_lock(void) { SDL_LockSpinlock(&g_tri_lock); }
|
||||
static void tri_unlock(void) { SDL_UnlockSpinlock(&g_tri_lock); }
|
||||
|
||||
static void tri_push(int type, const Uint8 *data, int len, jlong request)
|
||||
{
|
||||
if (len < 0) len = 0;
|
||||
if (len > TRITON_REPORT_BYTES + 1) len = TRITON_REPORT_BYTES + 1;
|
||||
tri_lock();
|
||||
int next = (g_tri_tail + 1) % TRI_QUEUE;
|
||||
if (next != g_tri_head) { /* full: drop (Steam re-sends settings and haptics constantly) */
|
||||
TritonReq *r = &g_tri_queue[g_tri_tail];
|
||||
r->type = type;
|
||||
r->len = len;
|
||||
r->request = request;
|
||||
if (len) memcpy(r->data, data, (size_t)len);
|
||||
g_tri_tail = next;
|
||||
}
|
||||
tri_unlock();
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_example_dsedge_NativeBridge_nativeTritonOutput(JNIEnv *env, jclass c, jbyteArray data, jboolean feature)
|
||||
{
|
||||
(void)c;
|
||||
if (!data) return;
|
||||
jsize n = (*env)->GetArrayLength(env, data);
|
||||
if (n < 1) return;
|
||||
Uint8 buf[TRITON_REPORT_BYTES + 1];
|
||||
if (n > (jsize)sizeof(buf)) n = (jsize)sizeof(buf);
|
||||
(*env)->GetByteArrayRegion(env, data, 0, n, (jbyte *)buf);
|
||||
tri_push(feature ? TRI_REQ_FEATURE_SET : TRI_REQ_OUTPUT, buf, (int)n, 0);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_example_dsedge_NativeBridge_nativeTritonGetFeature(JNIEnv *env, jclass c, jlong request, jint reportId)
|
||||
{
|
||||
(void)env; (void)c;
|
||||
Uint8 id = (Uint8)reportId;
|
||||
tri_push(TRI_REQ_FEATURE_GET, &id, 1, request);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_example_dsedge_NativeBridge_nativeTritonRumble(JNIEnv *env, jclass c, jint left, jint right)
|
||||
{
|
||||
(void)env; (void)c;
|
||||
atomic_store(&g_tri_rl, left < 0 ? 0 : left > 65535 ? 65535 : left);
|
||||
atomic_store(&g_tri_rr, right < 0 ? 0 : right > 65535 ? 65535 : right);
|
||||
atomic_store(&g_tri_rumble_dirty, 1);
|
||||
}
|
||||
|
||||
/* ---- SDL thread -> Java ---- */
|
||||
static void tri_java_init(JNIEnv *env)
|
||||
{
|
||||
if (g_tri_state) return;
|
||||
g_tri_state = (*env)->GetStaticMethodID(env, g_cls, "onTritonState", "(I[B)V");
|
||||
g_tri_conn = (*env)->GetStaticMethodID(env, g_cls, "onTritonConnected", "(ZLjava/lang/String;)V");
|
||||
g_tri_feature = (*env)->GetStaticMethodID(env, g_cls, "onTritonFeature", "(J[B)V");
|
||||
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
|
||||
}
|
||||
|
||||
static void tri_send_conn(JNIEnv *env, bool on, const char *what)
|
||||
{
|
||||
if (!g_tri_conn) return;
|
||||
jstring s = (*env)->NewStringUTF(env, what ? what : "");
|
||||
(*env)->CallStaticVoidMethod(env, g_cls, g_tri_conn, (jboolean)on, s);
|
||||
(*env)->DeleteLocalRef(env, s);
|
||||
}
|
||||
|
||||
static void tri_send_bytes(JNIEnv *env, jmethodID m, jlong request, int id, const Uint8 *data, int len, bool with_request)
|
||||
{
|
||||
if (!m) return;
|
||||
jbyteArray arr = NULL;
|
||||
if (data && len > 0) {
|
||||
arr = (*env)->NewByteArray(env, len);
|
||||
if (!arr) return;
|
||||
(*env)->SetByteArrayRegion(env, arr, 0, len, (const jbyte *)data);
|
||||
}
|
||||
if (with_request) (*env)->CallStaticVoidMethod(env, g_cls, m, request, arr);
|
||||
else (*env)->CallStaticVoidMethod(env, g_cls, m, (jint)id, arr);
|
||||
if (arr) (*env)->DeleteLocalRef(env, arr);
|
||||
}
|
||||
|
||||
static const char *tri_kind(const TritonIface *t)
|
||||
{
|
||||
return triton_dongle(t->pid) ? "Steam Controller (2026) via wireless puck" : "Steam Controller (2026) via USB cable";
|
||||
}
|
||||
|
||||
static void tri_deactivate(JNIEnv *env, const char *why)
|
||||
{
|
||||
if (g_tri_active < 0) return;
|
||||
SDL_Log("triton: passthrough stopped (%s)", why);
|
||||
g_tri_active = -1;
|
||||
atomic_store(&g_tri_rl, 0);
|
||||
atomic_store(&g_tri_rr, 0);
|
||||
tri_send_conn(env, false, why);
|
||||
}
|
||||
|
||||
static void tri_close(JNIEnv *env, int i, const char *why)
|
||||
{
|
||||
if (!g_tri[i].dev) return;
|
||||
if (g_tri_active == i) tri_deactivate(env, why);
|
||||
SDL_hid_close(g_tri[i].dev);
|
||||
memset(&g_tri[i], 0, sizeof(g_tri[i]));
|
||||
}
|
||||
|
||||
static void tri_close_all(JNIEnv *env, const char *why)
|
||||
{
|
||||
for (int i = 0; i < TRITON_MAX_IFACES; i++) tri_close(env, i, why);
|
||||
}
|
||||
|
||||
static bool tri_is_open(const char *path)
|
||||
{
|
||||
for (int i = 0; i < TRITON_MAX_IFACES; i++) if (g_tri[i].dev && !strcmp(g_tri[i].path, path)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Lizard mode (the controller acting as a mouse + keyboard) off: SET_SETTINGS_VALUES, SETTING_LIZARD_MODE = 0.
|
||||
* Steam sends this itself once it owns the controller; doing it here as well keeps the phone free of stray
|
||||
* mouse/keyboard input before Steam has started. */
|
||||
static void tri_lizard_off(SDL_hid_device *dev)
|
||||
{
|
||||
Uint8 buf[TRITON_REPORT_BYTES] = { 0x01, 0x87, 0x03, 0x09, 0x00, 0x00 };
|
||||
SDL_hid_send_feature_report(dev, buf, sizeof(buf));
|
||||
}
|
||||
|
||||
static void tri_scan(JNIEnv *env)
|
||||
{
|
||||
SDL_hid_device_info *list = SDL_hid_enumerate(VALVE_VID, 0);
|
||||
for (SDL_hid_device_info *d = list; d; d = d->next) {
|
||||
if (!triton_pid(d->product_id) || !d->path) continue;
|
||||
/* The puck carries one controller per interface 2..5; the cable has a single controller interface. */
|
||||
if (triton_dongle(d->product_id) && (d->interface_number < 2 || d->interface_number > 5)) continue;
|
||||
if (!triton_dongle(d->product_id) && d->usage_page != 0 && d->usage_page < 0xff00) continue;
|
||||
if (d->interface_class == 3 && d->interface_subclass == 1) continue; /* boot keyboard / mouse (lizard mode) */
|
||||
if (tri_is_open(d->path)) continue;
|
||||
int slot = -1;
|
||||
for (int i = 0; i < TRITON_MAX_IFACES; i++) if (!g_tri[i].dev) { slot = i; break; }
|
||||
if (slot < 0) break;
|
||||
SDL_hid_device *dev = SDL_hid_open_path(d->path);
|
||||
if (!dev) {
|
||||
SDL_Log("triton: could not open %04x:%04x interface %d: %s", d->vendor_id, d->product_id, d->interface_number, SDL_GetError());
|
||||
continue;
|
||||
}
|
||||
SDL_hid_set_nonblocking(dev, 1);
|
||||
g_tri[slot].dev = dev;
|
||||
SDL_strlcpy(g_tri[slot].path, d->path, sizeof(g_tri[slot].path));
|
||||
g_tri[slot].iface = d->interface_number;
|
||||
g_tri[slot].pid = d->product_id;
|
||||
SDL_Log("triton: opened %04x:%04x interface %d", d->vendor_id, d->product_id, d->interface_number);
|
||||
if (!triton_dongle(d->product_id)) tri_lizard_off(dev);
|
||||
}
|
||||
SDL_hid_free_enumeration(list);
|
||||
}
|
||||
|
||||
static void tri_run_queue(JNIEnv *env)
|
||||
{
|
||||
for (;;) {
|
||||
TritonReq r;
|
||||
tri_lock();
|
||||
bool have = g_tri_head != g_tri_tail;
|
||||
if (have) { r = g_tri_queue[g_tri_head]; g_tri_head = (g_tri_head + 1) % TRI_QUEUE; }
|
||||
tri_unlock();
|
||||
if (!have) return;
|
||||
SDL_hid_device *dev = g_tri_active >= 0 ? g_tri[g_tri_active].dev : NULL;
|
||||
if (r.type == TRI_REQ_FEATURE_GET) {
|
||||
Uint8 buf[TRITON_REPORT_BYTES + 1] = { 0 };
|
||||
buf[0] = r.data[0];
|
||||
int n = dev ? SDL_hid_get_feature_report(dev, buf, TRITON_REPORT_BYTES) : -1;
|
||||
tri_send_bytes(env, g_tri_feature, r.request, 0, n > 0 ? buf : NULL, n > 0 ? n : 0, true);
|
||||
} else if (dev && r.type == TRI_REQ_FEATURE_SET) {
|
||||
Uint8 buf[TRITON_REPORT_BYTES] = { 0 };
|
||||
int n = r.len > TRITON_REPORT_BYTES ? TRITON_REPORT_BYTES : r.len;
|
||||
memcpy(buf, r.data, (size_t)n);
|
||||
SDL_hid_send_feature_report(dev, buf, TRITON_REPORT_BYTES);
|
||||
} else if (dev && r.type == TRI_REQ_OUTPUT) {
|
||||
SDL_hid_write(dev, r.data, (size_t)r.len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Game rumble for the passed-through controller (DroidDeck's virtual-pad rumble): haptic rumble report 0x80,
|
||||
* re-sent every 40 ms while on, like SDL's own driver does. */
|
||||
static void tri_rumble(Uint64 now)
|
||||
{
|
||||
if (g_tri_active < 0) return;
|
||||
int dirty = atomic_exchange(&g_tri_rumble_dirty, 0);
|
||||
int l = atomic_load(&g_tri_rl), r = atomic_load(&g_tri_rr);
|
||||
if (!dirty && !(l || r)) return;
|
||||
if (!dirty && now - g_tri_rumble_ms < TRITON_RUMBLE_RESEND_MS) return;
|
||||
Uint8 msg[10] = { 0x80, 0, 0, 0, (Uint8)l, (Uint8)(l >> 8), 0, (Uint8)r, (Uint8)(r >> 8), 0 };
|
||||
SDL_hid_write(g_tri[g_tri_active].dev, msg, sizeof(msg));
|
||||
g_tri_rumble_ms = now;
|
||||
}
|
||||
|
||||
/* off_why: NULL = pass the controller through; otherwise why not (SDL3 driver off, or Steam Native Hook-up,
|
||||
* which hands the Steam Controller (2026) to Steam as itself instead -- see hookup.h). */
|
||||
static void triton_poll(JNIEnv *env, Uint64 now, const char *off_why)
|
||||
{
|
||||
tri_java_init(env);
|
||||
if (off_why) {
|
||||
tri_close_all(env, off_why);
|
||||
return;
|
||||
}
|
||||
Uint32 changes = SDL_hid_device_change_count();
|
||||
if (changes != g_tri_changes || now - g_tri_scan_ms > 3000) {
|
||||
g_tri_changes = changes;
|
||||
g_tri_scan_ms = now;
|
||||
tri_scan(env);
|
||||
}
|
||||
for (int i = 0; i < TRITON_MAX_IFACES; i++) {
|
||||
TritonIface *t = &g_tri[i];
|
||||
for (int reads = 0; t->dev && reads < 32; reads++) {
|
||||
Uint8 buf[TRITON_REPORT_BYTES];
|
||||
int n = SDL_hid_read(t->dev, buf, sizeof(buf));
|
||||
if (n == 0) break;
|
||||
if (n < 0) { tri_close(env, i, "controller unplugged"); break; }
|
||||
Uint8 id = buf[0];
|
||||
if (id == 0x42 || id == 0x45 || id == 0x47) {
|
||||
if (g_tri_active < 0) {
|
||||
g_tri_active = i;
|
||||
SDL_Log("triton: passing through interface %d", t->iface);
|
||||
tri_send_conn(env, true, tri_kind(t));
|
||||
tri_lizard_off(t->dev);
|
||||
g_tri_lizard_ms = now;
|
||||
}
|
||||
if (g_tri_active != i) continue;
|
||||
/* The wired state report (0x42) has the same layout as the Bluetooth one (0x45) that
|
||||
* DroidDeck's Steam Controller node declares, so it is relabelled; 0x47 keeps its id. */
|
||||
int len = n - 1 < TRITON_STATE_PAYLOAD ? n - 1 : TRITON_STATE_PAYLOAD;
|
||||
tri_send_bytes(env, g_tri_state, 0, id == 0x42 ? 0x45 : id, buf + 1, len, false);
|
||||
} else if ((id == 0x79 || id == 0x46) && n >= 2) {
|
||||
/* Puck wireless status: 1 = controller went away, 2 = connected. */
|
||||
if (buf[1] == 1 && g_tri_active == i) tri_deactivate(env, "controller turned off");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (g_tri_active >= 0) {
|
||||
tri_run_queue(env);
|
||||
tri_rumble(now);
|
||||
if (now - g_tri_lizard_ms > TRITON_LIZARD_REFRESH_MS) {
|
||||
g_tri_lizard_ms = now;
|
||||
tri_lizard_off(g_tri[g_tri_active].dev);
|
||||
}
|
||||
} else {
|
||||
tri_run_queue(env); /* answers pending feature reads with "no data" */
|
||||
}
|
||||
}
|
||||
|
||||
static bool triton_active(void) { return g_tri_active >= 0; }
|
||||
@@ -0,0 +1,71 @@
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def contained(directory, relative):
|
||||
path = directory / relative
|
||||
if path.is_symlink() or not path.resolve().is_relative_to(directory.resolve()):
|
||||
raise ValueError('Controller source path escapes its directory: ' + relative)
|
||||
return path
|
||||
|
||||
|
||||
def prepare(root=ROOT, output=None):
|
||||
root = root.resolve()
|
||||
build = root / 'app/build'
|
||||
output = output or build / 'controller-sources'
|
||||
if output.is_symlink() or output.resolve() == build.resolve() or not output.resolve().is_relative_to(build.resolve()):
|
||||
raise ValueError('Controller sources must be generated below app/build')
|
||||
output = output.resolve()
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix='controller-sources-', dir=output.parent) as temporary:
|
||||
stage = Path(temporary)
|
||||
for name in ('sdlbridge', 'sdl3'):
|
||||
vendor = root / 'third_party' / name
|
||||
manifest = json.loads((vendor / 'upstream.json').read_text(encoding='utf-8'))
|
||||
if manifest.get('version') != 1:
|
||||
raise ValueError('Unsupported controller source manifest: ' + name)
|
||||
source = vendor / 'upstream'
|
||||
files = manifest['files']
|
||||
actual = {p.relative_to(source).as_posix() for p in source.rglob('*') if p.is_file()}
|
||||
if set(files) != actual:
|
||||
raise ValueError('Vendored controller source inventory changed: ' + name)
|
||||
for relative, metadata in files.items():
|
||||
original = contained(source, relative)
|
||||
if hashlib.sha256(original.read_bytes()).hexdigest() != metadata['sha256']:
|
||||
raise ValueError('Vendored controller source hash changed: ' + name + '/' + relative)
|
||||
destination = contained(stage / name, relative)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(original, destination)
|
||||
shutil.copyfile(vendor / 'upstream.json', stage / name / 'upstream.json')
|
||||
for relative in manifest['patches']:
|
||||
patch = contained(vendor, relative)
|
||||
for line in patch.read_text(encoding='utf-8').splitlines():
|
||||
if line.startswith(('--- ', '+++ ')):
|
||||
filename = line[4:].split('\t', 1)[0]
|
||||
if filename[:2] not in ('a/', 'b/') or filename[2:] not in files:
|
||||
raise ValueError('Patch modifies an unlisted controller source: ' + filename)
|
||||
result = subprocess.run(['git', '-c', 'core.autocrlf=false', '-c', 'core.eol=lf',
|
||||
'apply', '--no-index', '--whitespace=nowarn',
|
||||
'--directory=' + (stage / name).relative_to(root).as_posix(), str(patch)],
|
||||
cwd=root, capture_output=True, text=True)
|
||||
if result.returncode:
|
||||
raise ValueError(name + '/' + relative + ': ' + result.stderr.strip())
|
||||
if output.exists():
|
||||
shutil.rmtree(output)
|
||||
shutil.copytree(stage, output)
|
||||
print('Verified and prepared pinned SDL3 and bridge sources.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description='Verify vendored controller snapshots and apply local patches.')
|
||||
parser.add_argument('--output', type=Path)
|
||||
args = parser.parse_args()
|
||||
prepare(output=args.output)
|
||||
@@ -0,0 +1,71 @@
|
||||
import difflib
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.prepare_controller_sources import prepare
|
||||
|
||||
|
||||
class ControllerSourcesTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name)
|
||||
for name in ('sdlbridge', 'sdl3'):
|
||||
vendor = self.root / 'third_party' / name
|
||||
(vendor / 'upstream/java').mkdir(parents=True)
|
||||
(vendor / 'patches').mkdir()
|
||||
(vendor / 'upstream/java/Input.java').write_bytes(b'upstream\n')
|
||||
patch = ''.join(difflib.unified_diff(['upstream\n'], ['embedded\n'],
|
||||
fromfile='a/java/Input.java', tofile='b/java/Input.java'))
|
||||
(vendor / 'patches/embed.patch').write_text(patch, encoding='utf-8', newline='\n')
|
||||
manifest = {'version': 1, 'source': {'commit': 'a' * 40},
|
||||
'files': {'java/Input.java': {'sha256': hashlib.sha256(b'upstream\n').hexdigest()}},
|
||||
'patches': ['patches/embed.patch']}
|
||||
(vendor / 'upstream.json').write_text(json.dumps(manifest), encoding='utf-8')
|
||||
|
||||
def test_prepares_patched_sources_without_changing_snapshots(self):
|
||||
prepare(self.root)
|
||||
for name in ('sdlbridge', 'sdl3'):
|
||||
self.assertEqual(b'embedded\n', (self.root / 'app/build/controller-sources' / name / 'java/Input.java').read_bytes())
|
||||
self.assertEqual(b'upstream\n', (self.root / 'third_party' / name / 'upstream/java/Input.java').read_bytes())
|
||||
self.assertTrue((self.root / 'app/build/controller-sources' / name / 'upstream.json').is_file())
|
||||
|
||||
def test_rejects_changed_snapshot_before_replacing_previous_output(self):
|
||||
output = self.root / 'app/build/controller-sources'
|
||||
output.mkdir(parents=True)
|
||||
(output / 'previous').write_text('keep')
|
||||
(self.root / 'third_party/sdlbridge/upstream/java/Input.java').write_bytes(b'drift\n')
|
||||
with self.assertRaisesRegex(ValueError, 'hash changed'):
|
||||
prepare(self.root)
|
||||
self.assertEqual('keep', (output / 'previous').read_text())
|
||||
|
||||
def test_accepts_a_relative_output_path(self):
|
||||
previous = Path.cwd()
|
||||
try:
|
||||
os.chdir(self.root)
|
||||
prepare(self.root, Path('app/build/relative'))
|
||||
finally:
|
||||
os.chdir(previous)
|
||||
self.assertEqual(b'embedded\n', (self.root / 'app/build/relative/sdlbridge/java/Input.java').read_bytes())
|
||||
|
||||
def test_fails_when_an_upstream_update_breaks_a_patch(self):
|
||||
vendor = self.root / 'third_party/sdlbridge'
|
||||
(vendor / 'upstream/java/Input.java').write_bytes(b'new upstream\n')
|
||||
manifest = json.loads((vendor / 'upstream.json').read_text())
|
||||
manifest['files']['java/Input.java']['sha256'] = hashlib.sha256(b'new upstream\n').hexdigest()
|
||||
(vendor / 'upstream.json').write_text(json.dumps(manifest))
|
||||
with self.assertRaisesRegex(ValueError, 'patch does not apply'):
|
||||
prepare(self.root)
|
||||
self.assertFalse((self.root / 'app/build/controller-sources').exists())
|
||||
|
||||
def test_refuses_output_outside_the_build_directory(self):
|
||||
with self.assertRaisesRegex(ValueError, 'below app/build'):
|
||||
prepare(self.root, self.root / 'third_party')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user