Compare commits

...
Author SHA1 Message Date
Kurt Himebauch 33ebc24647 chore: merge main into feat/bt-controller-trinket 2026-11-24 01:29:57 -05:00
Kurt Himebauch f9729d10e4 chore: merge main into feat/bt-controller-trinket 2026-11-23 10:01:57 -05:00
Kurt Himebauch c98be87383 chore: merge main into feat/bt-controller-trinket 2026-11-23 09:23:06 -05:00
Kurt Himebauch e854bf8403 chore: merge main into feat/bt-controller-trinket 2026-11-19 19:16:22 -05:00
Kurt Himebauch bdb240b640 fix: explain missing location permission on the Bluetooth controller screen 2026-11-19 15:10:26 -05:00
Kurt Himebauch 0a6060d409 chore: merge main into feat/bt-controller-trinket 2026-11-19 15:02:05 -05:00
Kurt Himebauch 81d2643a88 chore: merge main into feat/bt-controller-trinket 2026-11-17 23:59:27 -05:00
Kurt Himebauch 1099b82044 chore: merge main into feat/bt-controller-trinket 2026-11-17 20:31:07 -05:00
Kurt Himebauch dae53c29e0 chore: merge main into feat/bt-controller-trinket 2026-11-16 09:40:35 -05:00
Kurt Himebauch d168705954 chore: merge main into feat/bt-controller-trinket 2026-11-13 13:17:11 -05:00
Kurt Himebauch 8ba8b12e78 test: include the Trinkets tab in nav tab expectations 2026-11-13 12:06:45 -05:00
Kurt Himebauch aade03b7cf chore: merge main into feat/bt-controller-trinket 2026-11-13 11:47:32 -05:00
Kurt Himebauch eaa12a3594 chore: merge main into feat/bt-controller-trinket 2026-11-11 14:12:25 -05:00
Kurt Himebauch b3fc6b9a2c fix: drop on-screen touches when the controller screen loses focus 2026-11-06 12:43:22 -05:00
Kurt Himebauch 643496ae70 fix: release held pad input when the controller screen loses focus 2026-11-06 12:33:26 -05:00
Kurt Himebauch 1288874810 chore: merge main into feat/bt-controller-trinket 2026-11-06 12:18:55 -05:00
Kurt Himebauch 2510b5e113 fix: keep sending input when the host never raises the packet size 2026-11-03 07:47:32 -05:00
Kurt Himebauch 38cda8131d fix: full pairing instructions and narrow-screen header for the Bluetooth controller 2026-11-02 21:38:28 -05:00
Kurt Himebauch 4cebd09aa6 fix: only bonded hosts get controller input 2026-11-02 21:30:36 -05:00
Kurt Himebauch fce3daaf45 fix: use the whole screen for the Bluetooth controller layout 2026-11-02 21:25:35 -05:00
Kurt Himebauch 88a648c273 fix: address review feedback on the Bluetooth controller 2026-11-02 21:14:55 -05:00
Kurt Himebauch 6ead4af37e feat: Trinkets tab with a Bluetooth controller mode 2026-11-02 20:58:14 -05:00
10 changed files with 1869 additions and 7 deletions

No files matched your search

+11
View File
@@ -57,7 +57,10 @@
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.vulkan.version" android:version="0x401000" android:required="true" />
@@ -118,6 +121,14 @@
</intent-filter>
</activity>
<activity
android:name=".BtControllerActivity"
android:exported="false"
android:launchMode="singleTask"
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation|uiMode"
android:theme="@style/AppTheme" />
<activity
android:name=".DeviceCodeActivity"
android:exported="false"
@@ -0,0 +1,589 @@
package com.droiddeck.launcher
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.waitForUpOrCancellation
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.core.AppLanguage
import com.droiddeck.launcher.input.bt.BtGamepad
import com.droiddeck.launcher.input.bt.BtPadProfile
import com.droiddeck.launcher.input.bt.BtPadState
import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.ui.LocalPalette
import com.droiddeck.launcher.ui.PrimaryButton
import com.droiddeck.launcher.ui.SecondaryButton
import kotlin.math.hypot
import kotlin.math.roundToInt
class BtControllerActivity : ComponentActivity() {
private val physical = BtPadState()
private val touch = BtPadState()
private val merged = BtPadState()
private var keyButtons = 0
private var hatButtons = 0
private var touchEpoch by mutableStateOf(0)
private val main = Handler(Looper.getMainLooper())
private val exitHold = Runnable { finish() }
private var exitArmed = false
private var profile by mutableStateOf(BtPadProfile.GENERIC)
private var showTouch by mutableStateOf(true)
private var permissionDenied by mutableStateOf(false)
private var locationDenied by mutableStateOf(false)
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
val prefs = prefs(this)
profile = BtPadProfile.byId(prefs.getString(KEY_PROFILE, null))
showTouch = prefs.getBoolean(KEY_TOUCH, true)
val wanted = if (Build.VERSION.SDK_INT >= 31) NEARBY + LOCATION else LOCATION
val missing = wanted.filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
if (missing.isEmpty()) startPad() else requestPermissions(missing.toTypedArray(), REQUEST_NEARBY)
setContent { DroidDeckTheme { Screen() } }
}
private fun openAppInfo() {
runCatching {
startActivity(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, android.net.Uri.fromParts("package", packageName, null)))
}
}
override fun onResume() {
super.onResume()
locationDenied = LOCATION.any { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
if (permissionDenied && Build.VERSION.SDK_INT >= 31 && NEARBY.all { checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED }) {
permissionDenied = false
startPad()
}
}
private fun startPad() {
BtGamepad.start(this, profile)
BtGamepad.openPairingWindow()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode != REQUEST_NEARBY) return
val nearbyDenied = Build.VERSION.SDK_INT >= 31 && NEARBY.any { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
permissionDenied = nearbyDenied
locationDenied = LOCATION.any { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
if (!nearbyDenied) startPad()
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) return
physical.set(BtPadState())
touch.set(BtPadState())
touchEpoch++
keyButtons = 0
hatButtons = 0
push()
}
override fun onDestroy() {
main.removeCallbacks(exitHold)
if (isFinishing) BtGamepad.stop()
super.onDestroy()
}
private fun pickProfile(p: BtPadProfile) {
if (p == profile) return
profile = p
prefs(this).edit().putString(KEY_PROFILE, p.id).apply()
BtGamepad.switchProfile(p)
}
private fun push() {
physical.buttons = keyButtons or hatButtons
merged.merge(physical, touch)
BtGamepad.update(merged)
val combo = BtPadState.SELECT or BtPadState.START
val held = physical.buttons and combo == combo
if (held && !exitArmed) main.postDelayed(exitHold, EXIT_HOLD_MS)
else if (!held && exitArmed) main.removeCallbacks(exitHold)
exitArmed = held
}
private fun isPad(event: KeyEvent): Boolean {
val s = event.source
return s and InputDevice.SOURCE_GAMEPAD == InputDevice.SOURCE_GAMEPAD ||
s and InputDevice.SOURCE_JOYSTICK == InputDevice.SOURCE_JOYSTICK ||
KeyEvent.isGamepadButton(event.keyCode)
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
val bit = KEYS[event.keyCode]
if (bit == null || event.keyCode in DPAD_KEYS && !isPad(event) && event.source and InputDevice.SOURCE_DPAD != InputDevice.SOURCE_DPAD) {
return super.dispatchKeyEvent(event)
}
when (event.action) {
KeyEvent.ACTION_DOWN -> keyButtons = keyButtons or bit
KeyEvent.ACTION_UP -> keyButtons = keyButtons and bit.inv()
}
push()
return true
}
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
if (event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK || event.action != MotionEvent.ACTION_MOVE) {
return super.dispatchGenericMotionEvent(event)
}
val device = event.device
fun axis(code: Int): Float {
val range = device?.getMotionRange(code, event.source) ?: return 0f
val v = event.getAxisValue(code)
return if (Math.abs(v) > maxOf(range.flat, 0.04f)) v else 0f
}
val hasZ = device?.getMotionRange(MotionEvent.AXIS_Z, event.source) != null
physical.lx = axis(MotionEvent.AXIS_X); physical.ly = axis(MotionEvent.AXIS_Y)
physical.rx = axis(if (hasZ) MotionEvent.AXIS_Z else MotionEvent.AXIS_RX)
physical.ry = axis(if (hasZ) MotionEvent.AXIS_RZ else MotionEvent.AXIS_RY)
physical.lt = maxOf(axis(MotionEvent.AXIS_LTRIGGER), axis(MotionEvent.AXIS_BRAKE))
physical.rt = maxOf(axis(MotionEvent.AXIS_RTRIGGER), axis(MotionEvent.AXIS_GAS))
val hx = event.getAxisValue(MotionEvent.AXIS_HAT_X)
val hy = event.getAxisValue(MotionEvent.AXIS_HAT_Y)
hatButtons = (if (hy < -0.5f) BtPadState.UP else 0) or (if (hy > 0.5f) BtPadState.DOWN else 0) or
(if (hx < -0.5f) BtPadState.LEFT else 0) or (if (hx > 0.5f) BtPadState.RIGHT else 0)
push()
return true
}
private fun touchButton(bit: Int, down: Boolean) {
touch.buttons = if (down) touch.buttons or bit else touch.buttons and bit.inv()
if (bit == BtPadState.LT) touch.lt = if (down) 1f else 0f
if (bit == BtPadState.RT) touch.rt = if (down) 1f else 0f
push()
}
private fun touchStick(left: Boolean, x: Float, y: Float) {
if (left) { touch.lx = x; touch.ly = y } else { touch.rx = x; touch.ry = y }
push()
}
@Composable
private fun Screen() {
val status by BtGamepad.status.collectAsState()
val colors = MaterialTheme.colorScheme
Column(Modifier.fillMaxSize().background(colors.background).padding(horizontal = 12.dp, vertical = 8.dp)) {
Panel(status)
if (showTouch) {
TouchPad(Modifier.weight(1f).fillMaxWidth().padding(top = 6.dp), status)
} else {
Column(Modifier.weight(1f).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally) {
Instructions(status, Modifier.widthIn(max = 480.dp))
Text(stringResource(R.string.btpad_physical_hint), fontSize = 15.sp, color = colors.onSurfaceVariant)
}
}
}
}
@Composable
private fun Panel(status: BtGamepad.Status) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val connected = status.phase == BtGamepad.Phase.CONNECTED
BoxWithConstraints(Modifier.fillMaxWidth()) {
val narrow = maxWidth < 600.dp
val types: @Composable (Modifier) -> Unit = { m ->
Row(m.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
BtPadProfile.entries.forEach { p -> Chip(profileLabel(p), p == profile) { pickProfile(p) } }
Chip(stringResource(R.string.btpad_touch), showTouch) {
showTouch = !showTouch
prefs(this@BtControllerActivity).edit().putBoolean(KEY_TOUCH, showTouch).apply()
}
}
}
Column {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Box(Modifier.size(10.dp).clip(CircleShape).background(status.lightbar?.let { Color(it) } ?: if (connected) pal.signal else colors.onSurfaceVariant.copy(alpha = 0.4f)))
Column(if (narrow) Modifier.weight(1f) else Modifier.widthIn(max = 220.dp)) {
Text(shortStatus(status), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(stringResource(if (connected) R.string.btpad_exit_hint else R.string.btpad_switch_hint), fontSize = 11.sp,
color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
if (!narrow) types(Modifier.weight(1f))
if (locationDenied && !permissionDenied && !connected) SecondaryButton(stringResource(R.string.btpad_permission_open), compact = true) { openAppInfo() }
if (permissionDenied) PrimaryButton(stringResource(R.string.btpad_permission_open), compact = true) { openAppInfo() }
else if (connected) SecondaryButton(stringResource(R.string.btpad_disconnect), compact = true) { BtGamepad.disconnect() }
else PrimaryButton(stringResource(R.string.btpad_pair), compact = true, enabled = status.phase == BtGamepad.Phase.READY) { BtGamepad.openPairingWindow() }
SecondaryButton(stringResource(R.string.btpad_close), compact = true) { finish() }
}
if (narrow) types(Modifier.padding(top = 6.dp))
}
}
}
@Composable
private fun shortStatus(status: BtGamepad.Status): String =
if (status.phase == BtGamepad.Phase.READY && !permissionDenied) stringResource(R.string.btpad_status_waiting) else statusText(status)
@Composable
private fun Instructions(status: BtGamepad.Status, modifier: Modifier, size: androidx.compose.ui.unit.TextUnit = 14.sp) {
if (status.phase == BtGamepad.Phase.CONNECTED) return
val text = statusText(status) + if (locationDenied && !permissionDenied) "\n\n" + stringResource(R.string.btpad_location_hint) else ""
Text(text, fontSize = size, color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = androidx.compose.ui.text.style.TextAlign.Center, modifier = modifier)
}
@Composable
private fun statusText(status: BtGamepad.Status): String = if (permissionDenied) stringResource(R.string.btpad_status_permission) else when (status.phase) {
BtGamepad.Phase.OFF, BtGamepad.Phase.STARTING -> stringResource(R.string.btpad_status_starting)
BtGamepad.Phase.BLUETOOTH_OFF -> stringResource(R.string.btpad_status_bt_off)
BtGamepad.Phase.UNSUPPORTED -> stringResource(R.string.btpad_status_unsupported)
BtGamepad.Phase.READY -> stringResource(R.string.btpad_status_ready, status.name ?: "")
BtGamepad.Phase.CONNECTING -> stringResource(R.string.btpad_status_connecting, status.host ?: "")
BtGamepad.Phase.CONNECTED -> stringResource(R.string.btpad_status_connected, status.host ?: "")
}
@Composable
private fun profileLabel(p: BtPadProfile) = stringResource(when (p) {
BtPadProfile.GENERIC -> R.string.btpad_profile_generic
BtPadProfile.XBOX -> R.string.btpad_profile_xbox
BtPadProfile.DUALSHOCK4 -> R.string.btpad_profile_ds4
BtPadProfile.DUALSENSE -> R.string.btpad_profile_dualsense
BtPadProfile.STEAM -> R.string.btpad_profile_steam
})
@Composable
private fun Chip(label: String, on: Boolean, enabled: Boolean = true, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Text(label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold,
color = if (on) colors.background else if (enabled) colors.onBackground else colors.onSurfaceVariant,
modifier = Modifier.clip(CircleShape).background(if (on) pal.signal else colors.surface)
.border(1.dp, if (on) pal.signal else pal.line2, CircleShape)
.clickable(enabled = enabled, onClick = onClick).padding(horizontal = 12.dp, vertical = 6.dp))
}
@Composable
private fun TouchPad(modifier: Modifier, status: BtGamepad.Status) {
val lightbar = status.lightbar
val sony = profile == BtPadProfile.DUALSHOCK4 || profile == BtPadProfile.DUALSENSE
val steam = profile == BtPadProfile.STEAM
BoxWithConstraints(modifier) {
val w = maxWidth
val h = maxHeight
val stick = minOf(h * (if (steam) 0.38f else 0.46f), w * 0.2f)
val face = stick * 0.4f
val cluster = face * 3f
val shoulderW = minOf(w * 0.09f, stick * 0.75f)
val shoulderH = minOf(h * 0.13f, 44.dp)
val small = shoulderH * 0.85f
@Composable
fun at(fx: Float, fy: Float, bw: Dp, bh: Dp, content: @Composable () -> Unit) {
val x = (w * fx - bw / 2).coerceIn(0.dp, w - bw)
val y = (h * fy - bh / 2).coerceIn(0.dp, h - bh)
Box(Modifier.offset(x, y).size(bw, bh), contentAlignment = Alignment.Center) { content() }
}
val shoulderY = shoulderH / h / 2f
at(0.0f, shoulderY, shoulderW, shoulderH) { PadButton(if (sony) "L2" else "LT", BtPadState.LT, shoulderW, shoulderH) }
val second = (shoulderW * 1.5f + 8.dp) / w
at(second, shoulderY, shoulderW, shoulderH) { PadButton(if (sony) "L1" else "LB", BtPadState.LB, shoulderW, shoulderH) }
at(1f - second, shoulderY, shoulderW, shoulderH) { PadButton(if (sony) "R1" else "RB", BtPadState.RB, shoulderW, shoulderH) }
at(1.0f, shoulderY, shoulderW, shoulderH) { PadButton(if (sony) "R2" else "RT", BtPadState.RT, shoulderW, shoulderH) }
val menuW = shoulderW * 0.95f
val menu = listOfNotNull(
Triple(if (sony) "Share" else "View", BtPadState.SELECT, null),
Triple(if (sony) "PS" else if (steam) "Steam" else "Home", BtPadState.GUIDE, lightbar),
if (steam) Triple("···", BtPadState.SHARE, null) else null,
Triple(if (sony) "Options" else "Menu", BtPadState.START, null),
)
menu.forEachIndexed { i, (label, bit, tint) ->
val fx = 0.5f + (i - (menu.size - 1) / 2f) * ((menuW + 8.dp) / w)
at(fx, shoulderY, menuW, small) { PadButton(label, bit, menuW, small, tint = tint?.let { Color(it) }) }
}
val steamPad = minOf(h * 0.4f, w * 0.2f)
val infoW = if (steam) w * 0.4f - steamPad - 12.dp else w * 0.3f
val infoH = if (steam) h * 0.3f else h * 0.22f
at(0.5f, if (steam) 0.72f else 0.3f, infoW, infoH) { Instructions(status, Modifier.fillMaxWidth(), if (steam) 12.sp else 14.sp) }
if (steam) {
val rearY = (shoulderH * 1.6f) / h
at(0.0f, rearY, shoulderW, small) { PadButton("L5", BtPadState.L5, shoulderW, small) }
at(second, rearY, shoulderW, small) { PadButton("L4", BtPadState.L4, shoulderW, small) }
at(1f - second, rearY, shoulderW, small) { PadButton("R4", BtPadState.R4, shoulderW, small) }
at(1.0f, rearY, shoulderW, small) { PadButton("R5", BtPadState.R5, shoulderW, small) }
val pad = steamPad
at(0.11f, 0.5f, stick, stick) { Stick(stick, left = true) }
at(0.89f, 0.5f, stick, stick) { Stick(stick, left = false) }
at(0.3f, 0.34f, cluster, cluster) { Cross(face) }
at(0.7f, 0.34f, cluster, cluster) { Diamond(face, false) }
at(0.3f, 1f, pad, pad) { Trackpad(pad, left = true) }
at(0.7f, 1f, pad, pad) { Trackpad(pad, left = false) }
at(0.44f, 0.94f, menuW, small) { PadButton("L3", BtPadState.L3, menuW, small) }
at(0.56f, 0.94f, menuW, small) { PadButton("R3", BtPadState.R3, menuW, small) }
} else {
at(0.12f, 0.45f, stick, stick) { Stick(stick, left = true) }
at(0.88f, 0.45f, cluster, cluster) { Diamond(face, sony) }
at(0.32f, 0.78f, cluster, cluster) { Cross(face) }
at(0.68f, 0.78f, stick, stick) { Stick(stick, left = false) }
at(0.42f, 0.5f, menuW, small) { PadButton("L3", BtPadState.L3, menuW, small) }
at(0.58f, 0.5f, menuW, small) { PadButton("R3", BtPadState.R3, menuW, small) }
if (sony) at(0.5f, 0.68f, menuW * 1.6f, small * 1.4f) { PadButton("Touchpad", BtPadState.TOUCHPAD, menuW * 1.6f, small * 1.4f) }
}
}
}
@Composable
private fun Trackpad(size: Dp, left: Boolean) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var dot by remember { mutableStateOf<Offset?>(null) }
val px = with(LocalDensity.current) { size.toPx() }
Box(
Modifier.size(size).clip(RoundedCornerShape(18.dp)).background(colors.surface).border(1.dp, pal.line2, RoundedCornerShape(18.dp))
.pointerInput(left, touchEpoch) {
awaitEachGesture {
val first = awaitFirstDown(requireUnconsumed = false)
val started = first.uptimeMillis
fun norm(p: Offset) = Offset((p.x / this.size.width * 2f - 1f).coerceIn(-1f, 1f), (p.y / this.size.height * 2f - 1f).coerceIn(-1f, 1f))
var moved = 0f
var last = norm(first.position)
dot = last
touchPad(left, last, true)
var upTime = started
try {
while (true) {
val change = awaitPointerEvent().changes.firstOrNull { it.id == first.id } ?: break
if (!change.pressed) { upTime = change.uptimeMillis; break }
change.consume()
val p = norm(change.position)
moved += (p - last).getDistance()
last = p
dot = p
touchPad(left, p, true)
}
} catch (e: kotlinx.coroutines.CancellationException) {
dot = null
touchPad(left, last, false)
throw e
}
dot = null
if (upTime - started < TAP_MS && moved < 0.15f) clickPad(left, last)
else touchPad(left, last, false)
}
},
) {
dot?.let { d ->
val r = px * 0.08f
Box(Modifier.offset { IntOffset(((d.x + 1f) / 2f * px - r).roundToInt(), ((d.y + 1f) / 2f * px - r).roundToInt()) }
.size(size * 0.16f).clip(CircleShape).background(pal.signal))
}
}
}
private fun touchPad(left: Boolean, p: Offset, down: Boolean) {
val bit = if (left) BtPadState.LPAD_TOUCH else BtPadState.RPAD_TOUCH
touch.buttons = if (down) touch.buttons or bit else touch.buttons and bit.inv()
if (left) { touch.lpx = p.x; touch.lpy = p.y } else { touch.rpx = p.x; touch.rpy = p.y }
push()
}
private fun clickPad(left: Boolean, p: Offset) {
val click = if (left) BtPadState.LPAD_CLICK else BtPadState.RPAD_CLICK
touch.buttons = touch.buttons or click
touchPad(left, p, true)
main.postDelayed({
touch.buttons = touch.buttons and click.inv()
touchPad(left, p, false)
}, CLICK_MS)
}
@Composable
private fun Cross(size: Dp) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
PadButton("▲", BtPadState.UP, size, size)
Row {
PadButton("◀", BtPadState.LEFT, size, size)
Spacer(Modifier.size(size))
PadButton("▶", BtPadState.RIGHT, size, size)
}
PadButton("▼", BtPadState.DOWN, size, size)
}
}
@Composable
private fun Diamond(size: Dp, sony: Boolean) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
PadButton(if (sony) "△" else "Y", BtPadState.Y, size, size, round = true)
Row {
PadButton(if (sony) "□" else "X", BtPadState.X, size, size, round = true)
Spacer(Modifier.size(size))
PadButton(if (sony) "○" else "B", BtPadState.B, size, size, round = true)
}
PadButton(if (sony) "✕" else "A", BtPadState.A, size, size, round = true)
}
}
@Composable
private fun PadButton(label: String, bit: Int, width: Dp, height: Dp, round: Boolean = false, tint: Color? = null) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var down by remember { mutableStateOf(false) }
val shape = if (round) CircleShape else RoundedCornerShape(10.dp)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(width, height).clip(shape)
.background(if (down) pal.signal else tint?.copy(alpha = 0.35f) ?: colors.surface)
.border(1.dp, pal.line2, shape)
.pointerInput(bit, touchEpoch) {
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false)
down = true; touchButton(bit, true)
try {
waitForUpOrCancellation()
} finally {
down = false; touchButton(bit, false)
}
}
},
) {
Text(label, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = if (down) colors.background else colors.onBackground)
}
}
@Composable
private fun Stick(size: Dp, left: Boolean) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var knob by remember { mutableStateOf(Offset.Zero) }
val px = with(LocalDensity.current) { size.toPx() }
val knobSize = size * 0.42f
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(size).clip(CircleShape).background(colors.surface).border(1.dp, pal.line2, CircleShape)
.pointerInput(left, touchEpoch) {
awaitEachGesture {
val first = awaitFirstDown(requireUnconsumed = false)
val radius = this.size.width / 2f
val center = Offset(radius, this.size.height / 2f)
fun move(p: Offset) {
var d = (p - center) / (radius * 0.8f)
val len = hypot(d.x, d.y)
if (len > 1f) d /= len
knob = d
touchStick(left, d.x, d.y)
}
move(first.position)
try {
while (true) {
val change = awaitPointerEvent().changes.firstOrNull { it.id == first.id } ?: break
if (!change.pressed) break
change.consume()
move(change.position)
}
} finally {
knob = Offset.Zero
touchStick(left, 0f, 0f)
}
}
},
) {
val travel = px * 0.29f
Box(Modifier.offset { IntOffset((knob.x * travel).roundToInt(), (knob.y * travel).roundToInt()) }
.size(knobSize).clip(CircleShape).background(if (knob != Offset.Zero) pal.signal else colors.onSurfaceVariant.copy(alpha = 0.5f)))
}
}
companion object {
private const val EXIT_HOLD_MS = 1_500L
private const val TAP_MS = 200L
private const val CLICK_MS = 90L
private const val REQUEST_NEARBY = 41
private val NEARBY = listOf("android.permission.BLUETOOTH_ADVERTISE", "android.permission.BLUETOOTH_CONNECT", "android.permission.BLUETOOTH_SCAN")
private val LOCATION = listOf("android.permission.ACCESS_FINE_LOCATION")
private const val KEY_PROFILE = "btpad_profile"
private const val KEY_TOUCH = "btpad_touch"
private fun prefs(c: Context) = c.getSharedPreferences("trinkets", Context.MODE_PRIVATE)
private val DPAD_KEYS = setOf(KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT)
private val KEYS = mapOf(
KeyEvent.KEYCODE_BUTTON_A to BtPadState.A,
KeyEvent.KEYCODE_BUTTON_B to BtPadState.B,
KeyEvent.KEYCODE_BUTTON_X to BtPadState.X,
KeyEvent.KEYCODE_BUTTON_Y to BtPadState.Y,
KeyEvent.KEYCODE_BUTTON_L1 to BtPadState.LB,
KeyEvent.KEYCODE_BUTTON_R1 to BtPadState.RB,
KeyEvent.KEYCODE_BUTTON_L2 to BtPadState.LT,
KeyEvent.KEYCODE_BUTTON_R2 to BtPadState.RT,
KeyEvent.KEYCODE_BUTTON_SELECT to BtPadState.SELECT,
KeyEvent.KEYCODE_BUTTON_START to BtPadState.START,
KeyEvent.KEYCODE_BUTTON_MODE to BtPadState.GUIDE,
KeyEvent.KEYCODE_BUTTON_THUMBL to BtPadState.L3,
KeyEvent.KEYCODE_BUTTON_THUMBR to BtPadState.R3,
KeyEvent.KEYCODE_BUTTON_C to BtPadState.L4,
KeyEvent.KEYCODE_BUTTON_Z to BtPadState.R4,
KeyEvent.KEYCODE_BUTTON_1 to BtPadState.L4,
KeyEvent.KEYCODE_BUTTON_2 to BtPadState.R4,
KeyEvent.KEYCODE_BUTTON_3 to BtPadState.L5,
KeyEvent.KEYCODE_BUTTON_4 to BtPadState.R5,
KeyEvent.KEYCODE_DPAD_UP to BtPadState.UP,
KeyEvent.KEYCODE_DPAD_DOWN to BtPadState.DOWN,
KeyEvent.KEYCODE_DPAD_LEFT to BtPadState.LEFT,
KeyEvent.KEYCODE_DPAD_RIGHT to BtPadState.RIGHT,
)
}
}
@@ -0,0 +1,609 @@
package com.droiddeck.launcher.input.bt
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothGattServer
import android.bluetooth.BluetoothGattServerCallback
import android.bluetooth.BluetoothGattService
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.bluetooth.le.AdvertiseData
import android.bluetooth.le.AdvertisingSet
import android.bluetooth.le.AdvertisingSetCallback
import android.bluetooth.le.AdvertisingSetParameters
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.os.ParcelUuid
import android.os.SystemClock
import android.os.VibrationEffect
import android.os.Vibrator
import android.util.Log
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.util.ArrayDeque
import java.util.UUID
@SuppressLint("MissingPermission")
object BtGamepad {
enum class Phase { OFF, STARTING, BLUETOOTH_OFF, UNSUPPORTED, READY, CONNECTING, CONNECTED }
data class Status(val phase: Phase, val host: String? = null, val lightbar: Int? = null, val name: String? = null)
private const val TAG = "BtGamepad"
private val _status = MutableStateFlow(Status(Phase.OFF))
val status: StateFlow<Status> = _status
private var handler: Handler? = null
private var app: Context? = null
private var server: BluetoothGattServer? = null
private var advertising = false
private var profile = BtPadProfile.GENERIC
private var encoder: BtPadEncoder = profile.encoder()
private val pendingServices = ArrayDeque<BluetoothGattService>()
private val reportRefs = HashMap<BluetoothGattCharacteristic, Pair<Int, Int>>()
private val inputChars = HashMap<Int, BluetoothGattCharacteristic>()
private val longReads = HashMap<Pair<String, BluetoothGattCharacteristic>, ByteArray>()
private val preparedWrites = HashMap<BluetoothGattCharacteristic, ByteArray>()
private var host: BluetoothDevice? = null
private var priorityLink: BluetoothGatt? = null
private var notifyPending = false
private var dirty = false
private var mtu = 23
private val latest = BtPadState()
private val sent = BtPadState()
private var sentOnce = false
private var vibrator: Vibrator? = null
@Volatile private var running = false
private var pairingUntil = 0L
private var pendingHost: BluetoothDevice? = null
private var fastLinkPending = false
private var notifiedAt = 0L
private const val NOTIFY_TIMEOUT_MS = 100L
private const val PAIRING_WINDOW_MS = 120_000L
private const val MAX_MTU = 517
private const val FAST_LINK_DELAY_MS = 1_500L
fun start(context: Context, p: BtPadProfile) {
val h = handler ?: init(context)
h.post {
running = true
if (server != null && p == profile) {
val attached = host
if (attached != null) publish(Phase.CONNECTED, attached) else publish(Phase.READY)
startAdvertising()
} else {
close()
profile = p
publish(Phase.STARTING)
open()
}
}
}
private fun init(context: Context): Handler {
val ctx = context.applicationContext
app = ctx
vibrator = ctx.getSystemService(Vibrator::class.java)
val t = HandlerThread("bt-gamepad").apply { start() }
val h = Handler(t.looper)
handler = h
val receiver = object : BroadcastReceiver() {
override fun onReceive(c: Context, intent: Intent) {
when (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)) {
BluetoothAdapter.STATE_ON -> h.post { if (running) open() }
BluetoothAdapter.STATE_TURNING_OFF, BluetoothAdapter.STATE_OFF -> h.post {
close()
publish(Phase.BLUETOOTH_OFF)
}
}
}
}
ctx.registerReceiver(receiver, IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED), null, h)
val bonds = object : BroadcastReceiver() {
override fun onReceive(c: Context, intent: Intent) {
if (intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1) != BluetoothDevice.BOND_BONDED) return
h.post {
val waiting = pendingHost ?: return@post
if (waiting.bondState == BluetoothDevice.BOND_BONDED) attach(waiting)
}
}
}
ctx.registerReceiver(bonds, IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED), null, h)
return h
}
fun stop() {
val h = handler ?: return
h.post {
running = false
rumble(0, 0)
pairingUntil = 0
keepScanning()
stopAdvertising()
h.removeCallbacks(periodic)
dropFastLink()
pendingHost?.let { d -> runCatching { server?.cancelConnection(d) } }
pendingHost = null
host?.let { d -> runCatching { server?.cancelConnection(d) } }
host = null
longReads.clear()
_status.value = Status(Phase.OFF)
}
}
fun switchProfile(p: BtPadProfile) {
val h = handler ?: return
h.post {
if (p == profile && server != null) return@post
profile = p
close()
publish(Phase.STARTING)
h.postDelayed(::open, 300)
}
}
fun update(s: BtPadState) {
val h = handler ?: return
synchronized(latest) { latest.set(s) }
h.post(::sendIfChanged)
}
fun openPairingWindow() {
val h = handler ?: return
h.post {
pairingUntil = System.currentTimeMillis() + PAIRING_WINDOW_MS
keepScanning()
if (host == null) {
stopAdvertising()
startAdvertising()
}
}
}
private fun keepScanning() {
val adapter = adapter() ?: return
val h = handler ?: return
h.removeCallbacks(scanTick)
if (host != null || System.currentTimeMillis() > pairingUntil) {
runCatching { if (adapter.isDiscovering) adapter.cancelDiscovery() }
return
}
runCatching { if (!adapter.isDiscovering) adapter.startDiscovery() }
h.postDelayed(scanTick, 2_000)
}
private val scanTick = Runnable { keepScanning() }
fun disconnect() {
handler?.post { host?.let { d -> server?.cancelConnection(d) } }
}
private fun manager() = app?.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager
private fun adapter(): BluetoothAdapter? = manager()?.adapter
private fun open() {
val ctx = app ?: return
if (server != null || !running) return
val manager = manager()
val adapter = manager?.adapter
if (adapter == null || !ctx.packageManager.hasSystemFeature("android.hardware.bluetooth_le")) {
publish(Phase.UNSUPPORTED)
return
}
if (!adapter.isEnabled) {
publish(Phase.BLUETOOTH_OFF)
return
}
if (adapter.bluetoothLeAdvertiser == null) {
publish(Phase.UNSUPPORTED)
return
}
encoder = profile.encoder()
sentOnce = false
val s = runCatching { manager.openGattServer(ctx, serverCallback) }
.onFailure { Log.w(TAG, "no GATT server", it) }.getOrNull()
if (s == null) {
publish(Phase.UNSUPPORTED)
return
}
server = s
pendingServices.clear()
pendingServices.add(deviceInfoService())
pendingServices.add(hidService())
addNextService()
}
private fun close() {
stopAdvertising()
pairingUntil = 0
keepScanning()
dropFastLink()
server?.let { s ->
runCatching { manager()?.getConnectedDevices(BluetoothProfile.GATT_SERVER)?.forEach { s.cancelConnection(it) } }
runCatching { s.clearServices(); s.close() }
}
server = null
host = null
pendingHost = null
notifyPending = false
dirty = false
reportRefs.clear()
inputChars.clear()
longReads.clear()
preparedWrites.clear()
}
private fun addNextService() {
val s = server ?: return
val next = pendingServices.pollFirst()
if (next == null) {
Log.i(TAG, "${profile.id}: services ready")
startAdvertising()
return
}
if (!s.addService(next)) {
Log.w(TAG, "addService ${next.uuid} refused")
publish(Phase.UNSUPPORTED)
}
}
private fun deviceInfoService(): BluetoothGattService {
val service = BluetoothGattService(uuid16(0x180A), BluetoothGattService.SERVICE_TYPE_PRIMARY)
val pnp = BtPadEncoder.bytes(0x02, profile.vendorId and 0xFF, profile.vendorId shr 8,
profile.productId and 0xFF, profile.productId shr 8, profile.version and 0xFF, profile.version shr 8)
service.addCharacteristic(readOnly(0x2A50, pnp))
service.addCharacteristic(readOnly(0x2A29, "DroidDeck".toByteArray()))
return service
}
private fun hidService(): BluetoothGattService {
val service = BluetoothGattService(uuid16(0x1812), BluetoothGattService.SERVICE_TYPE_PRIMARY)
service.addCharacteristic(readOnly(0x2A4A, BtPadEncoder.bytes(0x11, 0x01, 0x00, 0x02)))
service.addCharacteristic(readOnly(0x2A4B, encoder.descriptor))
service.addCharacteristic(BluetoothGattCharacteristic(uuid16(0x2A4C),
BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, BluetoothGattCharacteristic.PERMISSION_WRITE))
for ((id, type) in encoder.reports) {
val props = when (type) {
BtPadEncoder.INPUT -> BluetoothGattCharacteristic.PROPERTY_READ or BluetoothGattCharacteristic.PROPERTY_NOTIFY
BtPadEncoder.OUTPUT -> BluetoothGattCharacteristic.PROPERTY_READ or BluetoothGattCharacteristic.PROPERTY_WRITE or
BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE
else -> BluetoothGattCharacteristic.PROPERTY_READ or BluetoothGattCharacteristic.PROPERTY_WRITE
}
val chr = BluetoothGattCharacteristic(uuid16(0x2A4D), props,
BluetoothGattCharacteristic.PERMISSION_READ or BluetoothGattCharacteristic.PERMISSION_WRITE)
if (type == BtPadEncoder.INPUT) {
chr.addDescriptor(cccd())
inputChars[id] = chr
}
val ref = BluetoothGattDescriptor(uuid16(0x2908), BluetoothGattDescriptor.PERMISSION_READ)
@Suppress("DEPRECATION")
ref.value = BtPadEncoder.bytes(id, type)
chr.addDescriptor(ref)
reportRefs[chr] = id to type
service.addCharacteristic(chr)
}
return service
}
private fun readOnly(uuid: Int, value: ByteArray): BluetoothGattCharacteristic {
val chr = BluetoothGattCharacteristic(uuid16(uuid), BluetoothGattCharacteristic.PROPERTY_READ, BluetoothGattCharacteristic.PERMISSION_READ)
@Suppress("DEPRECATION")
chr.value = value
return chr
}
private fun cccd() = BluetoothGattDescriptor(uuid16(0x2902),
BluetoothGattDescriptor.PERMISSION_READ or BluetoothGattDescriptor.PERMISSION_WRITE)
private fun uuid16(v: Int): UUID = UUID.fromString("%08x-0000-1000-8000-00805f9b34fb".format(v))
private fun startAdvertising() {
val advertiser = adapter()?.bluetoothLeAdvertiser ?: return
if (advertising || server == null || host != null || !running) return
val params = AdvertisingSetParameters.Builder()
.setLegacyMode(true)
.setConnectable(true)
.setScannable(true)
.setInterval(AdvertisingSetParameters.INTERVAL_LOW)
.setTxPowerLevel(AdvertisingSetParameters.TX_POWER_HIGH)
.build()
val data = AdvertiseData.Builder()
.addServiceUuid(ParcelUuid(uuid16(0x1812)))
.setIncludeDeviceName(true)
.build()
advertising = runCatching { advertiser.startAdvertisingSet(params, data, null, null, null, advertiseCallback); true }
.onFailure { Log.w(TAG, "advertising refused", it) }.getOrDefault(false)
if (!advertising) publish(Phase.UNSUPPORTED)
}
private fun stopAdvertising() {
if (!advertising) return
advertising = false
runCatching { adapter()?.bluetoothLeAdvertiser?.stopAdvertisingSet(advertiseCallback) }
}
private val advertiseCallback = object : AdvertisingSetCallback() {
override fun onAdvertisingSetStarted(set: AdvertisingSet?, txPower: Int, status: Int) {
Log.i(TAG, "advertising status $status")
handler?.post {
if (status == ADVERTISE_SUCCESS) {
if (host == null) publish(Phase.READY)
} else {
advertising = false
publish(Phase.UNSUPPORTED)
}
}
}
}
private val serverCallback = object : BluetoothGattServerCallback() {
override fun onServiceAdded(status: Int, service: BluetoothGattService) {
handler?.post {
if (status != BluetoothGatt.GATT_SUCCESS) {
Log.w(TAG, "service ${service.uuid} failed: $status")
publish(Phase.UNSUPPORTED)
} else addNextService()
}
}
override fun onConnectionStateChange(device: BluetoothDevice, status: Int, newState: Int) {
handler?.post {
Log.i(TAG, "${device.address}: state $newState status $status bond ${device.bondState}")
if (newState == BluetoothProfile.STATE_CONNECTED) {
stopAdvertising()
if (!running) {
server?.cancelConnection(device)
return@post
}
mtu = 23
if (device.bondState == BluetoothDevice.BOND_BONDED) attach(device)
else if (host == null) publish(Phase.CONNECTING, device)
} else if (newState == BluetoothProfile.STATE_DISCONNECTED && pendingHost == device && host == null) {
pendingHost = null
publish(Phase.READY)
startAdvertising()
} else if (newState == BluetoothProfile.STATE_DISCONNECTED && host == device) {
host = null
rumble(0, 0)
dropFastLink()
publish(Phase.READY)
startAdvertising()
} else if (newState == BluetoothProfile.STATE_DISCONNECTED && host == null) {
publish(Phase.READY)
startAdvertising()
}
}
}
override fun onMtuChanged(device: BluetoothDevice, newMtu: Int) {
handler?.post {
mtu = newMtu
Log.i(TAG, "mtu $newMtu")
}
}
override fun onCharacteristicReadRequest(device: BluetoothDevice, requestId: Int, offset: Int, chr: BluetoothGattCharacteristic) {
handler?.post {
val key = device.address to chr
val value = if (offset > 0) longReads[key] ?: valueOf(chr, device) else valueOf(chr, device).also { longReads[key] = it }
val reply = if (offset >= value.size) ByteArray(0) else value.copyOfRange(offset, value.size)
server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, reply)
if (chr.uuid == uuid16(0x2A4B)) attach(device)
}
}
override fun onDescriptorReadRequest(device: BluetoothDevice, requestId: Int, offset: Int, descriptor: BluetoothGattDescriptor) {
handler?.post {
@Suppress("DEPRECATION")
val value = descriptor.value ?: if (descriptor.uuid == uuid16(0x2902)) BtPadEncoder.bytes(1, 0) else ByteArray(0)
val reply = if (offset >= value.size) ByteArray(0) else value.copyOfRange(offset, value.size)
server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, reply)
}
}
override fun onDescriptorWriteRequest(device: BluetoothDevice, requestId: Int, descriptor: BluetoothGattDescriptor,
preparedWrite: Boolean, responseNeeded: Boolean, offset: Int, value: ByteArray) {
handler?.post {
if (responseNeeded) server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value)
if (descriptor.uuid == uuid16(0x2902) && descriptor.characteristic in reportRefs && value.isNotEmpty() &&
value[0].toInt() and 1 != 0) {
attach(device)
handler?.postDelayed({ startFastLink(device) }, FAST_LINK_DELAY_MS)
}
}
}
override fun onCharacteristicWriteRequest(device: BluetoothDevice, requestId: Int, chr: BluetoothGattCharacteristic,
preparedWrite: Boolean, responseNeeded: Boolean, offset: Int, value: ByteArray) {
handler?.post {
if (device == host && preparedWrite) {
val old = preparedWrites[chr] ?: ByteArray(0)
val merged = old.copyOf(maxOf(old.size, offset + value.size))
value.copyInto(merged, offset)
preparedWrites[chr] = merged
} else if (device == host) written(chr, value)
if (responseNeeded) server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value)
}
}
override fun onExecuteWrite(device: BluetoothDevice, requestId: Int, execute: Boolean) {
handler?.post {
if (execute && device == host) preparedWrites.forEach { (chr, v) -> written(chr, v) }
preparedWrites.clear()
server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, null)
}
}
override fun onNotificationSent(device: BluetoothDevice, status: Int) {
handler?.post {
notifyPending = false
if (dirty) sendNow()
}
}
}
private fun valueOf(chr: BluetoothGattCharacteristic, device: BluetoothDevice): ByteArray {
val ref = reportRefs[chr]
if (ref == null) {
@Suppress("DEPRECATION")
return chr.value ?: ByteArray(0)
}
val (id, type) = ref
return when (type) {
BtPadEncoder.INPUT -> if (id == encoder.inputId() && device == host) encoder.input(current()) else ByteArray(0)
BtPadEncoder.FEATURE -> {
host?.let { d -> handler?.postDelayed({ startFastLink(d) }, FAST_LINK_DELAY_MS) }
encoder.feature(id).also { Log.i(TAG, "feature 0x%02x read -> %d".format(id, it?.size ?: -1)) } ?: ByteArray(0)
}
else -> ByteArray(0)
}
}
private fun written(chr: BluetoothGattCharacteristic, value: ByteArray) {
val (id, type) = reportRefs[chr] ?: return
when (type) {
BtPadEncoder.FEATURE -> {
Log.i(TAG, "feature 0x%02x write %d bytes".format(id, value.size))
encoder.setFeature(id, value)
}
BtPadEncoder.OUTPUT -> feedback(encoder.output(id, value))
}
}
private fun attach(device: BluetoothDevice) {
if (host != null || !running) return
if (device.bondState != BluetoothDevice.BOND_BONDED) {
pendingHost = device
publish(Phase.CONNECTING, device)
return
}
pendingHost = null
host = device
stopAdvertising()
pairingUntil = 0
keepScanning()
sentOnce = false
notifyPending = false
Log.i(TAG, "host ${device.address} attached")
publish(Phase.CONNECTED, device)
fastLinkPending = true
handler?.removeCallbacks(periodic)
handler?.post(periodic)
}
private fun startFastLink(device: BluetoothDevice) {
if (host != device || !fastLinkPending) return
fastLinkPending = false
requestFastLink(device)
}
private fun requestFastLink(device: BluetoothDevice) {
val ctx = app ?: return
dropFastLink()
priorityLink = runCatching {
device.connectGatt(ctx, false, object : BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
if (newState == BluetoothProfile.STATE_CONNECTED && !gatt.requestMtu(MAX_MTU)) {
gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH)
}
}
override fun onMtuChanged(gatt: BluetoothGatt, newMtu: Int, status: Int) {
handler?.post {
if (newMtu > mtu) mtu = newMtu
Log.i(TAG, "link mtu $newMtu")
}
gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH)
}
}, BluetoothDevice.TRANSPORT_LE)
}.getOrNull()
}
private fun dropFastLink() {
priorityLink?.let { runCatching { it.disconnect(); it.close() } }
priorityLink = null
}
private fun current(): BtPadState = BtPadState().also { s -> synchronized(latest) { s.set(latest) } }
private fun sendIfChanged() {
if (encoder.periodMs > 0) return
if (sentOnce && current().sameAs(sent)) return
sendNow()
}
private fun sendNow() {
val s = server ?: return
val device = host ?: return
if (notifyPending && SystemClock.elapsedRealtime() - notifiedAt < NOTIFY_TIMEOUT_MS) {
dirty = true
return
}
val state = current()
val (id, value) = encoder.report(state, mtu - 3)
val chr = inputChars[id] ?: return
val ok = runCatching {
if (Build.VERSION.SDK_INT >= 33) {
s.notifyCharacteristicChanged(device, chr, false, value) == BluetoothGatt.GATT_SUCCESS
} else {
@Suppress("DEPRECATION")
chr.value = value
@Suppress("DEPRECATION")
s.notifyCharacteristicChanged(device, chr, false)
}
}.getOrDefault(false)
dirty = !ok
notifyPending = ok
notifiedAt = SystemClock.elapsedRealtime()
if (ok) {
sent.set(state)
sentOnce = true
}
}
private val periodic: Runnable = object : Runnable {
override fun run() {
val h = handler ?: return
if (host == null) return
if (encoder.periodMs > 0 || dirty) sendNow()
h.postDelayed(this, if (encoder.periodMs > 0) encoder.periodMs else 50)
}
}
private fun feedback(f: BtFeedback?) {
f ?: return
if (f.strong >= 0) rumble(f.strong, f.weak)
if (f.lightbar != null) _status.value = _status.value.copy(lightbar = f.lightbar)
}
private fun rumble(strong: Int, weak: Int) {
val v = vibrator ?: return
val amplitude = maxOf(strong, weak * 2 / 3).coerceIn(0, 255)
runCatching {
if (amplitude == 0) v.cancel()
else v.vibrate(VibrationEffect.createOneShot(1_000, amplitude))
}
}
private fun publish(phase: Phase, device: BluetoothDevice? = null) {
if (!running) {
_status.value = Status(Phase.OFF)
return
}
val name = device?.let { runCatching { it.name }.getOrNull() ?: it.address }
val own = runCatching { adapter()?.name }.getOrNull()
_status.value = Status(phase, name, _status.value.lightbar.takeIf { phase == Phase.CONNECTED }, own)
}
}
@@ -0,0 +1,559 @@
package com.droiddeck.launcher.input.bt
import java.util.zip.CRC32
import kotlin.math.roundToInt
class BtPadState {
@JvmField var buttons = 0
@JvmField var lx = 0f
@JvmField var ly = 0f
@JvmField var rx = 0f
@JvmField var ry = 0f
@JvmField var lt = 0f
@JvmField var rt = 0f
@JvmField var lpx = 0f
@JvmField var lpy = 0f
@JvmField var rpx = 0f
@JvmField var rpy = 0f
fun isDown(bit: Int) = buttons and bit != 0
fun set(other: BtPadState) {
buttons = other.buttons; lx = other.lx; ly = other.ly; rx = other.rx; ry = other.ry; lt = other.lt; rt = other.rt
lpx = other.lpx; lpy = other.lpy; rpx = other.rpx; rpy = other.rpy
}
fun merge(a: BtPadState, b: BtPadState) {
buttons = a.buttons or b.buttons
lx = stronger(a.lx, b.lx); ly = stronger(a.ly, b.ly)
rx = stronger(a.rx, b.rx); ry = stronger(a.ry, b.ry)
lt = maxOf(a.lt, b.lt, if (isDown(LT)) 1f else 0f)
rt = maxOf(a.rt, b.rt, if (isDown(RT)) 1f else 0f)
val left = if (b.isDown(LPAD_TOUCH)) b else a
lpx = left.lpx; lpy = left.lpy
val right = if (b.isDown(RPAD_TOUCH)) b else a
rpx = right.rpx; rpy = right.rpy
}
fun sameAs(o: BtPadState) = buttons == o.buttons && lx == o.lx && ly == o.ly && rx == o.rx && ry == o.ry && lt == o.lt && rt == o.rt &&
lpx == o.lpx && lpy == o.lpy && rpx == o.rpx && rpy == o.rpy
fun hat(): Int {
val x = (if (isDown(RIGHT)) 1 else 0) - (if (isDown(LEFT)) 1 else 0)
val y = (if (isDown(DOWN)) 1 else 0) - (if (isDown(UP)) 1 else 0)
return when {
x == 0 && y == -1 -> 0
x == 1 && y == -1 -> 1
x == 1 && y == 0 -> 2
x == 1 && y == 1 -> 3
x == 0 && y == 1 -> 4
x == -1 && y == 1 -> 5
x == -1 && y == 0 -> 6
x == -1 && y == -1 -> 7
else -> -1
}
}
companion object {
const val A = 1 shl 0
const val B = 1 shl 1
const val X = 1 shl 2
const val Y = 1 shl 3
const val LB = 1 shl 4
const val RB = 1 shl 5
const val LT = 1 shl 6
const val RT = 1 shl 7
const val SELECT = 1 shl 8
const val START = 1 shl 9
const val GUIDE = 1 shl 10
const val L3 = 1 shl 11
const val R3 = 1 shl 12
const val UP = 1 shl 13
const val DOWN = 1 shl 14
const val LEFT = 1 shl 15
const val RIGHT = 1 shl 16
const val L4 = 1 shl 17
const val R4 = 1 shl 18
const val L5 = 1 shl 19
const val R5 = 1 shl 20
const val TOUCHPAD = 1 shl 21
const val SHARE = 1 shl 22
const val LPAD_TOUCH = 1 shl 23
const val RPAD_TOUCH = 1 shl 24
const val LPAD_CLICK = 1 shl 25
const val RPAD_CLICK = 1 shl 26
private fun stronger(a: Float, b: Float) = if (Math.abs(b) > Math.abs(a)) b else a
}
}
class BtFeedback(val strong: Int, val weak: Int, val lightbar: Int? = null)
enum class BtPadProfile(val id: String, val vendorId: Int, val productId: Int, val version: Int) {
GENERIC("generic", 0x1209, 0x0001, 0x0100),
XBOX("xbox", 0x045E, 0x0B13, 0x0509),
DUALSHOCK4("dualshock4", 0x054C, 0x09CC, 0x0100),
DUALSENSE("dualsense", 0x054C, 0x0CE6, 0x0100),
STEAM("steam", 0x28DE, 0x1303, 0x0100);
fun encoder(): BtPadEncoder = when (this) {
GENERIC -> GenericEncoder()
XBOX -> XboxEncoder()
DUALSHOCK4 -> DualShock4Encoder()
DUALSENSE -> DualSenseEncoder()
STEAM -> SteamControllerEncoder()
}
companion object {
fun byId(id: String?) = entries.firstOrNull { it.id == id } ?: GENERIC
}
}
abstract class BtPadEncoder {
abstract val descriptor: ByteArray
abstract val reports: List<Pair<Int, Int>>
abstract fun inputId(): Int
abstract fun input(s: BtPadState): ByteArray
open val periodMs = 0L
open fun report(s: BtPadState, limit: Int): Pair<Int, ByteArray> {
val v = input(s)
return inputId() to if (v.size > limit) v.copyOf(limit) else v
}
open fun feature(id: Int): ByteArray? = null
open fun setFeature(id: Int, data: ByteArray) {}
open fun output(id: Int, data: ByteArray): BtFeedback? = null
protected fun axis8(v: Float) = ((v.coerceIn(-1f, 1f) + 1f) * 127.5f).roundToInt().coerceIn(0, 255)
protected fun trigger8(v: Float) = (v.coerceIn(0f, 1f) * 255f).roundToInt()
protected fun ByteArray.le16(at: Int, v: Int) { this[at] = v.toByte(); this[at + 1] = (v shr 8).toByte() }
protected fun ByteArray.le32(at: Int, v: Long) { for (i in 0 until 4) this[at + i] = (v shr (8 * i)).toByte() }
protected fun ByteArray.sealCrc(seed: Int, id: Int): ByteArray {
val crc = CRC32()
crc.update(seed)
crc.update(id)
crc.update(this, 0, size - 4)
le32(size - 4, crc.value)
return this
}
companion object {
const val INPUT = 1
const val OUTPUT = 2
const val FEATURE = 3
fun bytes(vararg v: Int) = ByteArray(v.size) { v[it].toByte() }
}
}
private class GenericEncoder : BtPadEncoder() {
override val reports = listOf(1 to INPUT)
override val descriptor = bytes(
0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01,
0x05, 0x09, 0x19, 0x01, 0x29, 0x18, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x18, 0x81, 0x02,
0x05, 0x01, 0x09, 0x39, 0x15, 0x00, 0x25, 0x07, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x65, 0x14, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42,
0x65, 0x00, 0x75, 0x04, 0x95, 0x01, 0x81, 0x03,
0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0x81, 0x02,
0x05, 0x02, 0x09, 0xC5, 0x09, 0xC4, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x02, 0x81, 0x02,
0xC0,
)
override fun inputId() = 1
override fun input(s: BtPadState): ByteArray {
var b = 0
GENERIC_ORDER.forEachIndexed { i, bit -> if (s.isDown(bit)) b = b or (1 shl i) }
val hat = s.hat().let { if (it < 0) 8 else it }
return bytes(
b and 0xFF, (b shr 8) and 0xFF, (b shr 16) and 0xFF, hat,
axis8(s.lx), axis8(s.ly), axis8(s.rx), axis8(s.ry), trigger8(s.lt), trigger8(s.rt),
)
}
companion object {
private val GENERIC_ORDER = intArrayOf(
BtPadState.A, BtPadState.B, 0, BtPadState.X, BtPadState.Y, 0, BtPadState.LB, BtPadState.RB,
BtPadState.LT, BtPadState.RT, BtPadState.SELECT, BtPadState.START, BtPadState.GUIDE, BtPadState.L3, BtPadState.R3, 0,
BtPadState.L4, BtPadState.R4, BtPadState.L5, BtPadState.R5, BtPadState.TOUCHPAD, BtPadState.SHARE, 0, 0,
)
}
}
private class XboxEncoder : BtPadEncoder() {
override val reports = listOf(1 to INPUT, 3 to OUTPUT)
override val descriptor = bytes(
0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01,
0x09, 0x01, 0xA1, 0x00, 0x09, 0x30, 0x09, 0x31, 0x15, 0x00, 0x27, 0xFF, 0xFF, 0x00, 0x00, 0x95, 0x02, 0x75, 0x10, 0x81, 0x02, 0xC0,
0x09, 0x01, 0xA1, 0x00, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x27, 0xFF, 0xFF, 0x00, 0x00, 0x95, 0x02, 0x75, 0x10, 0x81, 0x02, 0xC0,
0x05, 0x02, 0x09, 0xC5, 0x15, 0x00, 0x26, 0xFF, 0x03, 0x95, 0x01, 0x75, 0x0A, 0x81, 0x02, 0x15, 0x00, 0x25, 0x00, 0x75, 0x06, 0x95, 0x01, 0x81, 0x03,
0x05, 0x02, 0x09, 0xC4, 0x15, 0x00, 0x26, 0xFF, 0x03, 0x95, 0x01, 0x75, 0x0A, 0x81, 0x02, 0x15, 0x00, 0x25, 0x00, 0x75, 0x06, 0x95, 0x01, 0x81, 0x03,
0x05, 0x01, 0x09, 0x39, 0x15, 0x01, 0x25, 0x08, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x66, 0x14, 0x00, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42,
0x75, 0x04, 0x95, 0x01, 0x15, 0x00, 0x25, 0x00, 0x35, 0x00, 0x45, 0x00, 0x65, 0x00, 0x81, 0x03,
0x05, 0x09, 0x19, 0x01, 0x29, 0x0F, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0F, 0x81, 0x02,
0x15, 0x00, 0x25, 0x00, 0x75, 0x01, 0x95, 0x01, 0x81, 0x03,
0x05, 0x0C, 0x0A, 0xB2, 0x00, 0x15, 0x00, 0x25, 0x01, 0x95, 0x01, 0x75, 0x01, 0x81, 0x02,
0x15, 0x00, 0x25, 0x00, 0x75, 0x07, 0x95, 0x01, 0x81, 0x03,
0x05, 0x0F, 0x09, 0x21, 0x85, 0x03, 0xA1, 0x02,
0x09, 0x97, 0x15, 0x00, 0x25, 0x01, 0x75, 0x04, 0x95, 0x01, 0x91, 0x02,
0x15, 0x00, 0x25, 0x00, 0x75, 0x04, 0x95, 0x01, 0x91, 0x03,
0x09, 0x70, 0x15, 0x00, 0x25, 0x64, 0x75, 0x08, 0x95, 0x04, 0x91, 0x02,
0x09, 0x50, 0x66, 0x01, 0x10, 0x55, 0x0E, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x01, 0x91, 0x02,
0x09, 0xA7, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x01, 0x91, 0x02,
0x65, 0x00, 0x55, 0x00, 0x09, 0x7C, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x01, 0x91, 0x02,
0xC0, 0xC0,
)
override fun inputId() = 1
override fun input(s: BtPadState): ByteArray {
val r = ByteArray(16)
r.le16(0, axis16(s.lx)); r.le16(2, axis16(s.ly)); r.le16(4, axis16(s.rx)); r.le16(6, axis16(s.ry))
r.le16(8, (s.lt.coerceIn(0f, 1f) * 1023f).roundToInt())
r.le16(10, (s.rt.coerceIn(0f, 1f) * 1023f).roundToInt())
r[12] = (s.hat() + 1).toByte()
var b = 0
XBOX_ORDER.forEachIndexed { i, bit -> if (bit != 0 && s.isDown(bit)) b = b or (1 shl i) }
r.le16(13, b)
r[15] = if (s.isDown(BtPadState.SHARE)) 1 else 0
return r
}
override fun output(id: Int, data: ByteArray): BtFeedback? {
if (id != 3) return null
val d = data
if (d.size < 5) return null
val enable = d[0].toInt()
val strong = if (enable and 0x02 != 0) d[3].toInt() and 0xFF else 0
val weak = if (enable and 0x01 != 0) d[4].toInt() and 0xFF else 0
return BtFeedback(strong * 255 / 100, weak * 255 / 100)
}
private fun axis16(v: Float) = ((v.coerceIn(-1f, 1f) + 1f) * 32767.5f).roundToInt().coerceIn(0, 65535)
companion object {
private val XBOX_ORDER = intArrayOf(
BtPadState.A, BtPadState.B, 0, BtPadState.X, BtPadState.Y, 0, BtPadState.LB, BtPadState.RB,
0, 0, BtPadState.SELECT, BtPadState.START, BtPadState.GUIDE, BtPadState.L3, BtPadState.R3,
)
}
}
private abstract class SonyEncoder : BtPadEncoder() {
@Volatile protected var enhanced = false
protected var counter = 0
protected var timestamp = 0L
override val periodMs = 8L
protected fun buttons(s: BtPadState): IntArray {
val hat = s.hat().let { if (it < 0) 8 else it }
var b0 = hat
if (s.isDown(BtPadState.X)) b0 = b0 or 0x10
if (s.isDown(BtPadState.A)) b0 = b0 or 0x20
if (s.isDown(BtPadState.B)) b0 = b0 or 0x40
if (s.isDown(BtPadState.Y)) b0 = b0 or 0x80
var b1 = 0
if (s.isDown(BtPadState.LB)) b1 = b1 or 0x01
if (s.isDown(BtPadState.RB)) b1 = b1 or 0x02
if (s.lt > 0.05f) b1 = b1 or 0x04
if (s.rt > 0.05f) b1 = b1 or 0x08
if (s.isDown(BtPadState.SELECT) || s.isDown(BtPadState.SHARE)) b1 = b1 or 0x10
if (s.isDown(BtPadState.START)) b1 = b1 or 0x20
if (s.isDown(BtPadState.L3)) b1 = b1 or 0x40
if (s.isDown(BtPadState.R3)) b1 = b1 or 0x80
var b2 = 0
if (s.isDown(BtPadState.GUIDE)) b2 = b2 or 0x01
if (s.isDown(BtPadState.TOUCHPAD)) b2 = b2 or 0x02
return intArrayOf(b0, b1, b2)
}
override fun report(s: BtPadState, limit: Int): Pair<Int, ByteArray> {
val full = input(s)
return if (full.size <= limit) inputId() to full else 1 to simple(s)
}
protected fun simple(s: BtPadState): ByteArray {
val b = buttons(s)
counter = (counter + 1) and 0x3F
return bytes(axis8(s.lx), axis8(s.ly), axis8(s.rx), axis8(s.ry), b[0], b[1], b[2] or (counter shl 2), trigger8(s.lt), trigger8(s.rt))
}
protected fun calibration(): ByteArray {
val r = ByteArray(40)
val v = intArrayOf(0, 0, 0, GYRO, -GYRO, GYRO, -GYRO, GYRO, -GYRO, GYRO_SPEED, GYRO_SPEED, ACCEL, -ACCEL, ACCEL, -ACCEL, ACCEL, -ACCEL)
v.forEachIndexed { i, x -> r.le16(i * 2, x) }
return r.sealCrc(FEATURE_SEED, 0x05)
}
override fun feature(id: Int): ByteArray? {
val reply = reply(id) ?: return null
enhanced = true
return reply
}
protected abstract fun reply(id: Int): ByteArray?
companion object {
const val INPUT_SEED = 0xA1
const val OUTPUT_SEED = 0xA2
const val FEATURE_SEED = 0xA3
const val GYRO = 8800
const val GYRO_SPEED = 540
const val ACCEL = 8192
}
}
private class DualShock4Encoder : SonyEncoder() {
override val reports = listOf(0x01 to INPUT, 0x11 to INPUT, 0x11 to OUTPUT, 0x02 to FEATURE, 0xA3 to FEATURE, 0x05 to FEATURE, 0x12 to FEATURE)
override val descriptor = bytes(
0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01,
0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0x81, 0x02,
0x09, 0x39, 0x15, 0x00, 0x25, 0x07, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x65, 0x14, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42, 0x65, 0x00,
0x05, 0x09, 0x19, 0x01, 0x29, 0x0E, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0E, 0x81, 0x02,
0x06, 0x00, 0xFF, 0x09, 0x20, 0x75, 0x06, 0x95, 0x01, 0x15, 0x00, 0x25, 0x7F, 0x81, 0x02,
0x05, 0x01, 0x09, 0x33, 0x09, 0x34, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x02, 0x81, 0x02,
0x06, 0x04, 0xFF,
0x85, 0x02, 0x09, 0x24, 0x95, 0x24, 0xB1, 0x02,
0x85, 0xA3, 0x09, 0x25, 0x95, 0x30, 0xB1, 0x02,
0x85, 0x05, 0x09, 0x26, 0x95, 0x28, 0xB1, 0x02,
0x85, 0x12, 0x09, 0x27, 0x95, 0x0F, 0xB1, 0x02,
0x85, 0x11, 0x09, 0x22, 0x95, 0x4D, 0x81, 0x02,
0x09, 0x23, 0x95, 0x4D, 0x91, 0x02,
0xC0,
)
override fun inputId() = if (enhanced) 0x11 else 0x01
override fun input(s: BtPadState): ByteArray {
if (!enhanced) return simple(s)
val r = ByteArray(77)
r[0] = 0xC0.toByte()
val b = buttons(s)
counter = (counter + 1) and 0x3F
timestamp += 1500
val c = 2
r[c] = axis8(s.lx).toByte(); r[c + 1] = axis8(s.ly).toByte(); r[c + 2] = axis8(s.rx).toByte(); r[c + 3] = axis8(s.ry).toByte()
r[c + 4] = b[0].toByte(); r[c + 5] = b[1].toByte(); r[c + 6] = (b[2] or (counter shl 2)).toByte()
r[c + 7] = trigger8(s.lt).toByte(); r[c + 8] = trigger8(s.rt).toByte()
r.le16(c + 9, timestamp.toInt())
r.le16(c + 20, ACCEL)
r[c + 29] = 0x09
r[c + 32] = 1
r[c + 34] = 0x80.toByte()
r[c + 38] = 0x80.toByte()
return r.sealCrc(INPUT_SEED, 0x11)
}
override fun reply(id: Int): ByteArray? = when (id) {
0x02 -> ByteArray(36).also { r ->
val v = intArrayOf(0, 0, 0, GYRO, GYRO, GYRO, -GYRO, -GYRO, -GYRO, GYRO_SPEED, GYRO_SPEED, ACCEL, -ACCEL, ACCEL, -ACCEL, ACCEL, -ACCEL)
v.forEachIndexed { i, x -> r.le16(i * 2, x) }
}
0x05 -> calibration()
0xA3 -> ByteArray(48).also { r ->
"Sep 21 2018".toByteArray().copyInto(r, 0)
"04:50:51".toByteArray().copyInto(r, 16)
r.le16(34, 0x0100)
r.le16(40, 0xA00A)
}
0x12 -> ByteArray(15).also { r -> FAKE_MAC.copyInto(r, 0); r[6] = 0x08; r[7] = 0x25 }
else -> null
}
override fun output(id: Int, data: ByteArray): BtFeedback? {
if (id != 0x11) return null
enhanced = true
val d = data
if (d.size < 10) return null
val flags = d[2].toInt()
val light = if (flags and 0x02 != 0) rgb(d[7], d[8], d[9]) else null
return BtFeedback(d[6].toInt() and 0xFF, d[5].toInt() and 0xFF, light)
}
}
private class DualSenseEncoder : SonyEncoder() {
override val reports = listOf(0x01 to INPUT, 0x31 to INPUT, 0x31 to OUTPUT, 0x05 to FEATURE, 0x09 to FEATURE, 0x20 to FEATURE)
override val descriptor = bytes(
0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01,
0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0x81, 0x02,
0x09, 0x39, 0x15, 0x00, 0x25, 0x07, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x65, 0x14, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42, 0x65, 0x00,
0x05, 0x09, 0x19, 0x01, 0x29, 0x0E, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0E, 0x81, 0x02,
0x06, 0x00, 0xFF, 0x09, 0x20, 0x75, 0x06, 0x95, 0x01, 0x15, 0x00, 0x25, 0x7F, 0x81, 0x02,
0x05, 0x01, 0x09, 0x33, 0x09, 0x34, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x02, 0x81, 0x02,
0x06, 0x00, 0xFF,
0x85, 0x31, 0x09, 0x31, 0x95, 0x4D, 0x81, 0x02,
0x09, 0x32, 0x95, 0x4D, 0x91, 0x02,
0x85, 0x05, 0x09, 0x33, 0x95, 0x28, 0xB1, 0x02,
0x85, 0x09, 0x09, 0x34, 0x95, 0x13, 0xB1, 0x02,
0x85, 0x20, 0x09, 0x35, 0x95, 0x3F, 0xB1, 0x02,
0xC0,
)
private var sequence = 0
override fun inputId() = if (enhanced) 0x31 else 0x01
override fun input(s: BtPadState): ByteArray {
if (!enhanced) return simple(s)
val r = ByteArray(77)
sequence = (sequence + 1) and 0xFF
timestamp += 24000
r[0] = 0x10
val c = 1
r[c] = axis8(s.lx).toByte(); r[c + 1] = axis8(s.ly).toByte(); r[c + 2] = axis8(s.rx).toByte(); r[c + 3] = axis8(s.ry).toByte()
r[c + 4] = trigger8(s.lt).toByte(); r[c + 5] = trigger8(s.rt).toByte()
r[c + 6] = sequence.toByte()
val b = buttons(s)
r[c + 7] = b[0].toByte(); r[c + 8] = b[1].toByte(); r[c + 9] = b[2].toByte()
r.le16(c + 23, ACCEL)
r.le32(c + 27, timestamp)
r[c + 32] = 0x80.toByte()
r[c + 36] = 0x80.toByte()
r[c + 52] = 0x09
return r.sealCrc(INPUT_SEED, 0x31)
}
override fun reply(id: Int): ByteArray? = when (id) {
0x05 -> calibration()
0x09 -> ByteArray(19).also { r -> FAKE_MAC.copyInto(r, 0) }.sealCrc(FEATURE_SEED, 0x09)
0x20 -> ByteArray(63).also { r ->
"Jun 19 2023".toByteArray().copyInto(r, 0)
"14:47:34".toByteArray().copyInto(r, 11)
r.le16(19, 0x0003)
r.le32(23, 0x00000615L)
r.le32(27, 0x0110002AL)
r.le16(43, 0x0630)
}.sealCrc(FEATURE_SEED, 0x20)
else -> null
}
override fun output(id: Int, data: ByteArray): BtFeedback? {
if (id != 0x31) return null
enhanced = true
val d = data
if (d.size < 49) return null
val flags0 = d[2].toInt()
val flags1 = d[3].toInt()
val light = if (flags1 and 0x04 != 0) rgb(d[46], d[47], d[48]) else null
return if (flags0 and 0x03 != 0) BtFeedback(d[5].toInt() and 0xFF, d[4].toInt() and 0xFF, light)
else if (light != null) BtFeedback(-1, -1, light) else null
}
}
private class SteamControllerEncoder : BtPadEncoder() {
override val descriptor = bytes(
0x06, 0x00, 0xFF, 0x09, 0x01, 0xA1, 0x01, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08,
0x85, 0x45, 0x09, 0x02, 0x95, 0x2D, 0x81, 0x02, 0x85, 0x47, 0x09, 0x03, 0x95, 0x2D, 0x81, 0x02,
0x85, 0x80, 0x09, 0x04, 0x95, 0x09, 0x91, 0x02, 0x85, 0x81, 0x09, 0x05, 0x95, 0x07, 0x91, 0x02,
0x85, 0x82, 0x09, 0x06, 0x95, 0x03, 0x91, 0x02, 0x85, 0x83, 0x09, 0x07, 0x95, 0x09, 0x91, 0x02,
0x85, 0x84, 0x09, 0x08, 0x95, 0x08, 0x91, 0x02, 0x85, 0x85, 0x09, 0x09, 0x95, 0x03, 0x91, 0x02,
0x85, 0x01, 0x09, 0x0A, 0x95, 0x3F, 0xB1, 0x02, 0xC0,
)
override val reports = listOf(0x45 to INPUT, 0x47 to INPUT, 0x80 to OUTPUT, 0x81 to OUTPUT, 0x82 to OUTPUT,
0x83 to OUTPUT, 0x84 to OUTPUT, 0x85 to OUTPUT, 0x01 to FEATURE)
override val periodMs = 8L
@Volatile private var pending = 0
private var packet = 0
private val start = System.nanoTime()
override fun inputId() = 0x45
override fun input(s: BtPadState): ByteArray {
val r = ByteArray(45)
packet++
r[0] = packet.toByte()
var b = LGRIP_TOUCH or RGRIP_TOUCH
BUTTONS.forEach { (mine, theirs) -> if (s.isDown(mine)) b = b or theirs }
if (s.lt >= 0.98f) b = b or LTRIGGER_CLICK
if (s.rt >= 0.98f) b = b or RTRIGGER_CLICK
if (Math.abs(s.lx) > 0.06f || Math.abs(s.ly) > 0.06f) b = b or LSTICK_TOUCH
if (Math.abs(s.rx) > 0.06f || Math.abs(s.ry) > 0.06f) b = b or RSTICK_TOUCH
r.le32(1, b.toLong())
r.le16(5, (s.lt.coerceIn(0f, 1f) * 32767f).roundToInt())
r.le16(7, (s.rt.coerceIn(0f, 1f) * 32767f).roundToInt())
r.le16(9, stick(s.lx)); r.le16(11, stick(-s.ly)); r.le16(13, stick(s.rx)); r.le16(15, stick(-s.ry))
if (s.isDown(BtPadState.LPAD_TOUCH)) {
r.le16(17, stick(s.lpx)); r.le16(19, stick(-s.lpy))
r.le16(21, if (s.isDown(BtPadState.LPAD_CLICK)) 32767 else 4000)
}
if (s.isDown(BtPadState.RPAD_TOUCH)) {
r.le16(23, stick(s.rpx)); r.le16(25, stick(-s.rpy))
r.le16(27, if (s.isDown(BtPadState.RPAD_CLICK)) 32767 else 4000)
}
r.le32(29, (System.nanoTime() - start) / 1000)
r.le16(37, 16384)
return r
}
override fun setFeature(id: Int, data: ByteArray) {
val d = data
if (id == 1 && d.isNotEmpty()) pending = d[0].toInt() and 0xFF
}
override fun feature(id: Int): ByteArray? {
if (id != 1) return null
val r = ByteArray(63)
r[0] = pending.toByte()
when (pending) {
0x83 -> {
val ids = intArrayOf(0x01, 0x02, 0x04, 0x09, 0x0A, 0x0B)
val values = longArrayOf(0x1303, 0, FW_TIMESTAMP, 72, 0, 4000)
r[1] = (ids.size * 5).toByte()
ids.forEachIndexed { i, a -> r[2 + i * 5] = a.toByte(); r.le32(3 + i * 5, values[i]) }
}
0xAE -> { r[1] = 0x14; r[2] = 0x01; SERIAL.toByteArray().copyInto(r, 3) }
0xBA -> { r[1] = 0x11; "DROIDDECKCHIP02".toByteArray().copyInto(r, 3) }
}
return r
}
override fun output(id: Int, data: ByteArray): BtFeedback? {
val d = data
return when (id) {
0x80 -> if (d.size >= 8) {
val left = (d[3].toInt() and 0xFF) or ((d[4].toInt() and 0xFF) shl 8)
val right = (d[6].toInt() and 0xFF) or ((d[7].toInt() and 0xFF) shl 8)
BtFeedback(left shr 8, right shr 8)
} else null
in 0x81..0x85 -> BtFeedback(0, 120)
else -> null
}
}
private fun stick(v: Float) = (v.coerceIn(-1f, 1f) * 32767f).roundToInt()
companion object {
private const val LGRIP_TOUCH = 0x20000000
private const val RGRIP_TOUCH = 0x10000000
private const val LTRIGGER_CLICK = 0x08000000
private const val RTRIGGER_CLICK = 0x00800000
private const val LSTICK_TOUCH = 0x01000000
private const val RSTICK_TOUCH = 0x00100000
private const val FW_TIMESTAMP = 0x6AC686B3L
private const val SERIAL = "DROIDDECKSC01"
private val BUTTONS = listOf(
BtPadState.A to 0x00000001, BtPadState.B to 0x00000002, BtPadState.X to 0x00000004, BtPadState.Y to 0x00000008,
BtPadState.SHARE to 0x00000010, BtPadState.R3 to 0x00000020, BtPadState.SELECT to 0x00000040,
BtPadState.R4 to 0x00000080, BtPadState.R5 to 0x00000100, BtPadState.RB to 0x00000200,
BtPadState.DOWN to 0x00000400, BtPadState.RIGHT to 0x00000800, BtPadState.LEFT to 0x00001000,
BtPadState.UP to 0x00002000, BtPadState.START to 0x00004000, BtPadState.L3 to 0x00008000,
BtPadState.GUIDE to 0x00010000, BtPadState.L4 to 0x00020000, BtPadState.L5 to 0x00040000,
BtPadState.LB to 0x00080000,
BtPadState.RPAD_TOUCH to 0x00200000, BtPadState.RPAD_CLICK to 0x00400000,
BtPadState.LPAD_TOUCH to 0x02000000, BtPadState.LPAD_CLICK to 0x04000000,
)
}
}
private val FAKE_MAC = BtPadEncoder.bytes(0x5D, 0x44, 0x33, 0x22, 0x11, 0xD0)
private fun rgb(r: Byte, g: Byte, b: Byte) =
(0xFF shl 24) or ((r.toInt() and 0xFF) shl 16) or ((g.toInt() and 0xFF) shl 8) or (b.toInt() and 0xFF)
@@ -271,6 +271,10 @@ private fun Content(
UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV))
return
}
if (selected == "trinkets") {
TrinketsPage(modifier.padding(horizontal = padH).padding(top = padV))
return
}
if (selected == "steam") {
SteamHome(s, a, modifier)
return
@@ -59,6 +59,7 @@ import androidx.compose.material.icons.filled.SdStorage
import androidx.compose.material.icons.filled.Movie
import androidx.compose.material.icons.filled.Sync
import androidx.compose.material.icons.filled.MoreHoriz
import androidx.compose.material.icons.filled.Toys
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.material3.Icon
@@ -205,6 +206,7 @@ internal fun railLabelIcon(key: String): Pair<Int, ImageVector> = when (key) {
"agent" -> R.string.rail_agent to Icons.Filled.Terminal
"android-apps" -> R.string.rail_apps to Icons.Filled.Apps
"setup" -> R.string.rail_setup to Icons.Filled.Settings
"trinkets" -> R.string.rail_trinkets to Icons.Filled.Toys
"storage" -> R.string.rail_storage to Icons.Filled.SdStorage
"sync" -> R.string.rail_sync to Icons.Filled.Sync
"decky" -> R.string.rail_decky to DeckyIcon
@@ -26,7 +26,7 @@ internal object DeveloperTools {
internal object NavTabs {
const val MORE = "more"
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
val DEFAULT_HIDDEN = setOf("android-apps", "agent")
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "android-apps", "agent")
@@ -0,0 +1,61 @@
package com.droiddeck.launcher.ui
import android.content.Intent
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.BluetoothConnected
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.BtControllerActivity
import com.droiddeck.launcher.R
@Composable
internal fun TrinketsPage(modifier: Modifier) {
val context = LocalContext.current
Column(modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(stringResource(R.string.trinkets_intro), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
Trinket(Icons.Outlined.BluetoothConnected, stringResource(R.string.btpad_title), stringResource(R.string.btpad_summary)) {
context.startActivity(Intent(context, BtControllerActivity::class.java))
}
}
}
@Composable
private fun Trinket(icon: ImageVector, title: String, summary: String, onOpen: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line2, Shape14).padding(14.dp),
) {
Box(Modifier.size(44.dp).clip(Shape12).background(pal.signal.copy(alpha = 0.14f)), contentAlignment = Alignment.Center) {
Icon(icon, null, tint = pal.signal)
}
Column(Modifier.weight(1f)) {
Text(title, fontSize = 16.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
Text(summary, fontSize = 13.sp, color = colors.onSurfaceVariant)
}
PrimaryButton(stringResource(R.string.trinkets_open), compact = true, onClick = onOpen)
}
}
+27
View File
@@ -1701,6 +1701,7 @@
<string name="rail_apps">Apps</string>
<string name="rail_setup">Settings</string>
<string name="rail_updates">Updates</string>
<string name="rail_trinkets">Trinkets</string>
<string name="rail_more">More</string>
<string name="more_edit_tabs">Edit tabs</string>
<string name="setup_group_tabs">Tabs</string>
@@ -4207,6 +4208,32 @@
<string name="stores_gamejolt_filter_status">Status</string>
<string name="stores_gamejolt_filter_partners">Partners</string>
<string name="stores_gamejolt_followed">Followed games</string>
<string name="trinkets_intro">Odds and ends that don\'t fit anywhere else.</string>
<string name="trinkets_open">Open</string>
<string name="btpad_title">Bluetooth controller</string>
<string name="btpad_summary">Use this device as a wireless gamepad for a PC, phone, or another handheld.</string>
<string name="btpad_exit_hint">Hold Select + Start to stop</string>
<string name="btpad_disconnect">Disconnect</string>
<string name="btpad_pair">Pair new</string>
<string name="btpad_permission_open">App info</string>
<string name="btpad_location_hint">Location is off for DroidDeck, so pairing requests show up as a notification instead of a prompt here. Allow Location in App info to fix that.</string>
<string name="btpad_status_permission">Allow Nearby devices for DroidDeck in App info to use this.</string>
<string name="btpad_close">Stop</string>
<string name="btpad_touch">Touch controls</string>
<string name="btpad_physical_hint">The built-in buttons and sticks are sent to the paired device.</string>
<string name="btpad_switch_hint">After changing the type, remove this device from the other side\'s Bluetooth list and pair again.</string>
<string name="btpad_status_starting">Starting Bluetooth controller…</string>
<string name="btpad_status_bt_off">Turn on Bluetooth to continue</string>
<string name="btpad_status_unsupported">This device\'s Bluetooth can\'t act as a controller</string>
<string name="btpad_status_ready">On the other device, add a Bluetooth device and pick %1$s. If it takes over 2 minutes, tap Pair new.</string>
<string name="btpad_status_waiting">Waiting for a device to pair</string>
<string name="btpad_status_connecting">Pairing with %1$s. Accept the request on this device.</string>
<string name="btpad_status_connected">Connected to %1$s</string>
<string name="btpad_profile_generic">Generic</string>
<string name="btpad_profile_xbox">Xbox</string>
<string name="btpad_profile_ds4">DualShock 4</string>
<string name="btpad_profile_dualsense">DualSense</string>
<string name="btpad_profile_steam">Steam Controller</string>
<string name="wow_chat_title">Chat input</string>
<string name="wow_chat_voice">Voice type</string>
<string name="wow_chat_remember">Remember this selection</string>
@@ -40,7 +40,7 @@ class NavTabsTest {
}
@Test fun aFreshInstallShowsTheDefaultBarMoreAndHiddenTabs() {
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", NavTabs.MORE), navigationKeys(state()))
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", NavTabs.MORE), navigationKeys(state()))
assertEquals(listOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state()))
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps"))
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "agent"))
@@ -51,7 +51,7 @@ class NavTabsTest {
@Test fun showingMusicOnceKeepsItShownAfterReload() {
place("soundtracks", TabPlace.BAR)
NavTabs.load(ctx)
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", NavTabs.MORE), navigationKeys(state()))
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", "soundtracks", NavTabs.MORE), navigationKeys(state()))
}
@Test fun shelvedTabsLeaveTheBarAndAddMoreAtTheEnd() {
@@ -77,7 +77,7 @@ class NavTabsTest {
NavTabs.reset(ctx)
NavTabs.load(ctx)
assertTrue(NavTabs.isDefault())
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", NavTabs.MORE), navigationKeys(state()))
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", NavTabs.MORE), navigationKeys(state()))
}
@Test fun anOldLayoutKeepsWhatItsSwitchesShowed() {
@@ -85,7 +85,7 @@ class NavTabsTest {
.putBoolean("gameStoresEnabled", false).putBoolean("soundtracksEnabled", false).commit()
NavTabs.load(ctx)
val s = state()
assertEquals(listOf("steam", "games", "desktop", "components", "setup", "updates", NavTabs.MORE), navigationKeys(s))
assertEquals(listOf("steam", "games", "desktop", "components", "setup", "updates", "trinkets", NavTabs.MORE), navigationKeys(s))
assertEquals(listOf("storage", "sync", "decky", "boot-movies"), NavTabs.more(s))
listOf("stores", "downloads", "soundtracks", "android-apps", "agent").forEach { assertEquals(it, TabPlace.HIDDEN, NavTabs.place(s, it)) }
val prefs = ctx.getSharedPreferences("session", Context.MODE_PRIVATE)
@@ -119,9 +119,9 @@ class NavTabsTest {
}
@Test fun tabsMissingFromASavedOrderSlotInAfterTheirDefaultNeighbour() {
assertEquals(listOf("updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "steam", "desktop", "games", "downloads", "setup"),
assertEquals(listOf("updates", "trinkets", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "steam", "desktop", "games", "downloads", "setup"),
NavTabs.arrange(listOf("updates", "steam")))
assertEquals(listOf("games", "downloads", "steam", "setup", "stores", "soundtracks", "desktop", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "updates"),
assertEquals(listOf("games", "downloads", "steam", "setup", "stores", "soundtracks", "desktop", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "updates", "trinkets"),
NavTabs.arrange(listOf("games", "steam", "setup", "stores", "desktop", "components", "android-apps", "updates", "bogus")))
}