Merge current main into PR #1174

This commit is contained in:
Kurt Himebauch committed 2026-10-22 12:13:52 -04:00
commit 0b616146ff
141 files changed
+6310 -274

No files matched your search

@@ -16,6 +16,7 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
com.droiddeck.launcher.ui.Themes.loadGradient(this)
// Helper processes must not initialize the main USB provider or guest graphics context.
val process = if (android.os.Build.VERSION.SDK_INT >= 28) Application.getProcessName()
else (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)
@@ -1622,6 +1622,7 @@ class MainActivity : ComponentActivity() {
pipAutoEnter = pipAutoEnter,
unfoldedControls = if (mode == SessionService.MODE_STEAM &&
com.droiddeck.launcher.session.SessionDisplay.foldable(this)) unfoldedControls else null,
unfoldedControlsWithController = unfoldedControlsWithController,
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
backActionsInverted = backActionsInverted,
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
@@ -1688,6 +1689,9 @@ class MainActivity : ComponentActivity() {
onZramCompression = { on -> SessionPrefs.setZramCompression(this, on); zramCompression = on },
onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this, on); pipAutoEnter = on },
onUnfoldedControls = { on -> SessionPrefs.setUnfoldedControls(this, on); unfoldedControls = on },
onUnfoldedControlsWithController = { on ->
SessionPrefs.setUnfoldedControlsWithController(this, on); unfoldedControlsWithController = on
},
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
onBackActionsInverted = { inverted ->
SessionPrefs.setBackActionsInverted(this, inverted)
@@ -1876,10 +1880,12 @@ class MainActivity : ComponentActivity() {
private var pipAutoEnter by mutableStateOf(false)
private var unfoldedControls by mutableStateOf(false)
private var unfoldedControlsWithController by mutableStateOf(false)
private fun loadModeSettings(mode: String) {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
unfoldedControls = SessionPrefs.unfoldedControls(this)
unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this)
resolution = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
fexPreset = SessionPrefs.fexPreset(this)
forceSsbs = SessionPrefs.forceSsbs(this)
@@ -134,6 +134,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var pipUi by mutableStateOf(false)
private var pipAutoEnter by mutableStateOf(false)
private var unfoldedControls by mutableStateOf(false)
private var unfoldedControlsWithController by mutableStateOf(false)
private var picturePosition by mutableStateOf("center")
private fun applyGameAlignment() {
@@ -366,17 +367,46 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
private var selectedSecondScreenDisplay by mutableStateOf(SessionState.secondScreenDisplay)
private var started = false
private var sessionActivityDisplayId = Display.DEFAULT_DISPLAY
private lateinit var displayManager: DisplayManager
private var secondScreenPresentation: SecondScreenPresentation? = null
private val displayListener = object : DisplayManager.DisplayListener {
override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays()
override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays()
override fun onDisplayAdded(displayId: Int) {
notifyActivityDisplayStateChanged(displayId)
refreshSecondScreenDisplays()
}
override fun onDisplayRemoved(displayId: Int) {
if (refreshActivityDisplayId() && started) {
SessionService.setActivityDisplay(this@SessionActivity, sessionActivityDisplayId)
}
refreshSecondScreenDisplays()
}
override fun onDisplayChanged(displayId: Int) {
notifyActivityDisplayStateChanged(displayId)
followPanelRefresh(displayId)
refreshSecondScreenDisplays()
}
}
@Suppress("DEPRECATION")
private fun currentActivityDisplayId(): Int = windowManager.defaultDisplay.displayId
private fun refreshActivityDisplayId(): Boolean {
val current = if (Build.VERSION.SDK_INT >= 30) display?.displayId ?: currentActivityDisplayId()
else currentActivityDisplayId()
val changed = sessionActivityDisplayId != current
sessionActivityDisplayId = current
SessionState.activityDisplayId = current
return changed
}
private fun notifyActivityDisplayStateChanged(changedDisplayId: Int) {
val changed = refreshActivityDisplayId()
if (started && (changed || changedDisplayId == sessionActivityDisplayId)) {
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
}
}
private fun followPanelRefresh(displayId: Int) {
if (!CompositorHost.isStarted) return
val output = glassesScreen?.display
@@ -923,6 +953,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
},
unfoldedControls = if (com.droiddeck.launcher.session.SessionDisplay.foldable(this@SessionActivity)) unfoldedControls else null,
onUnfoldedControls = ::chooseUnfoldedControls,
unfoldedControlsWithController = unfoldedControlsWithController,
onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController,
onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) },
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
@@ -1407,6 +1439,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun readPrefs() {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
unfoldedControls = SessionPrefs.unfoldedControls(this)
unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this)
picturePosition = SessionPrefs.picturePosition(this)
hudOn = SessionPrefs.hudEnabled(this)
hudFps = SessionPrefs.hudShowFps(this)
@@ -1678,7 +1711,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
intent.getStringExtra(SessionService.EXTRA_STEAM_UI),
intent.getStringExtra(SessionService.EXTRA_STEAM_URL),
intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS),
shownOnDisplayId,
sessionActivityDisplayId,
)
}
applyFrameGen()
@@ -1729,7 +1762,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
super.onConfigurationChanged(newConfig)
if (started) SessionService.setActivityDisplay(this, shownOnDisplayId)
if (refreshActivityDisplayId() && started) {
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
}
cancelTouchGestures()
applyFollowOrientation(newConfig)
applyUnfoldedControls()
@@ -2012,7 +2047,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (drawerOpen) {
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
drawerPage = sessionDrawerPages(SessionState.mode == SessionService.MODE_STEAM && secondScreenDisplays.isNotEmpty(), glasses.present)
drawerPage = sessionDrawerPages(secondScreenDisplays.isNotEmpty(), glasses.present)
.step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
releaseDrawerDirection()
}
@@ -2456,6 +2491,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
applyUnfoldedControls()
}
private fun chooseUnfoldedControlsWithController(on: Boolean) {
SessionPrefs.setUnfoldedControlsWithController(this, on)
unfoldedControlsWithController = on
applyUnfoldedControls()
}
private fun refreshControls() {
applyUnfoldedControls()
updateOnScreenControls()
@@ -2465,11 +2506,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (!::sessionRoot.isInitialized) return
val width = sessionRoot.width
val height = sessionRoot.height
val wanted = unfoldedControls && com.droiddeck.launcher.session.SessionDisplay.foldable(this) &&
!PadBridge.anyControllerConnected() && !SteamControllerBle.connected &&
SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad &&
!pipUi && !isInPictureInPictureMode && width > 0 && height > 0 &&
resources.configuration.smallestScreenWidthDp >= com.droiddeck.launcher.session.SessionDisplay.UNFOLDED_MIN_DP
val wanted = com.droiddeck.launcher.session.SessionDisplay.unfoldedControlsWanted(
enabled = unfoldedControls,
foldable = com.droiddeck.launcher.session.SessionDisplay.foldable(this),
controllerConnected = PadBridge.anyControllerConnected() || SteamControllerBle.connected,
keepWithController = unfoldedControlsWithController,
steamDeckPad = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad,
pip = pipUi || isInPictureInPictureMode,
width = width,
height = height,
smallestWidthDp = resources.configuration.smallestScreenWidthDp,
)
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height)
else FrameLayout.LayoutParams.MATCH_PARENT
val params = surfaceView.layoutParams as FrameLayout.LayoutParams
@@ -2888,11 +2935,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
super.onStart()
if (runtimeRemovalBlocked) return
started = true
refreshActivityDisplayId()
displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper()))
refreshSecondScreenDisplays()
if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
startedScreens++
SessionService.setActivityVisible(this, true, shownOnDisplayId)
SessionService.setActivityVisible(this, true, sessionActivityDisplayId)
Glasses.rescan()
updateGlassesScreen()
updateHandCamera()
@@ -2906,7 +2954,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
closeSecondScreen(reset = false)
startedScreens = (startedScreens - 1).coerceAtLeast(0)
updateGlassesScreen()
if (startedScreens == 0) SessionService.setActivityVisible(this, false)
if (startedScreens == 0) SessionService.setActivityVisible(this, false, sessionActivityDisplayId)
super.onStop()
}
@@ -2937,6 +2985,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onResume() {
super.onResume()
if (refreshActivityDisplayId() && started) {
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
}
applyFollowOrientation(resources.configuration)
if (runtimeRemovalBlocked) return
com.droiddeck.launcher.ui.Motion.refresh(this)
@@ -3418,7 +3469,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun finishFlooded() {
if (isFinishing) return
val signal = com.droiddeck.launcher.ui.Themes.byId(SessionPrefs.theme(this)).signal
val signal = com.droiddeck.launcher.ui.Themes.current(this).signal
com.droiddeck.launcher.ui.QuitFlood.mark(signal.toArgb())
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(signal.toArgb()))
quitFlooded = true
@@ -3449,7 +3500,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun completeLeave() {
if (isFinishing) return
val signal = com.droiddeck.launcher.ui.Themes.byId(SessionPrefs.theme(this)).signal
val signal = com.droiddeck.launcher.ui.Themes.current(this).signal
com.droiddeck.launcher.ui.QuitFlood.mark(signal.toArgb())
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(signal.toArgb()))
quitFlooded = true
@@ -6,6 +6,7 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -249,11 +250,11 @@ fun CollapsibleRail(
if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
shape,
)
.clickable(onClick = item.onClick)
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
.padding(horizontal = if (collapsed) 2.dp else 11.dp, vertical = if (collapsed) 6.dp else 9.dp)
} else {
base
.clickable(onClick = item.onClick)
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
.background(if (active) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
.padding(horizontal = if (collapsed) 2.dp else 13.dp, vertical = if (collapsed) 7.dp else 11.dp)
}
@@ -337,7 +338,7 @@ fun RailTopTabs(
.background(MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)),
)
links.forEach { link ->
TopTabCell(link.icon, link.label, selected = false, onClick = link.onClick, modifier = Modifier.weight(1f))
TopTabCell(link.icon, link.label, selected = false, onClick = link.onClick, isTab = false, modifier = Modifier.weight(1f))
}
}
}
@@ -352,6 +353,7 @@ private fun TopTabCell(
selected: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier,
isTab: Boolean = true,
) {
val tint = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
Column(
@@ -359,7 +361,13 @@ private fun TopTabCell(
modifier = modifier
.clip(RoundedCornerShape(9.dp))
.background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
.clickable(onClick = onClick)
.then(
if (isTab) {
Modifier.selectable(selected = selected, role = androidx.compose.ui.semantics.Role.Tab, onClick = onClick)
} else {
Modifier.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onClick)
},
)
.padding(vertical = 6.dp, horizontal = 1.dp),
) {
Icon(icon, contentDescription = label, tint = tint, modifier = Modifier.size(20.dp))
@@ -193,7 +193,7 @@ internal fun FileItemRow(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 3.dp)
.combinedClickable(
.combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
onClick = { if (selectionMode) onToggleSelect() else onTap() },
onLongClick = onLongPress,
),
@@ -302,7 +302,7 @@ internal fun ParentFolderRow(compact: Boolean = false, onTap: () -> Unit) {
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 3.dp)
.clickable(onClick = onTap),
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onTap),
shape = RoundedCornerShape(10.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
@@ -422,7 +422,7 @@ private fun FavoriteCard(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 3.dp)
.clickable(onClick = onJump),
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onJump),
shape = RoundedCornerShape(10.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
@@ -526,7 +526,7 @@ internal fun FileGridTile(
Card(
modifier = Modifier
.padding(4.dp)
.combinedClickable(
.combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
onClick = { if (selectionMode) onToggleSelect() else onTap() },
onLongClick = onLongPress,
),
@@ -43,6 +43,7 @@ data class GlassesState(
val volumeMax: Int = 8,
val sunblock: Boolean = false,
val hardwareControls: Boolean = true,
val supportsDisplayModeControl: Boolean = true,
val hasSunblock: Boolean = true,
val controlError: String? = null,
val tracking: Boolean = false,
@@ -64,7 +65,7 @@ data class GlassesState(
val spatialConnected: Boolean get() = canControl && supportsSpatial
fun usesSpatialControllers(settings: GlassesSettings) = spatialConnected && settings.positionalTracking &&
(settings.handControllers || settings.joyConTracking)
val can3d: Boolean get() = canControl && !noSignal && sbsSupport != SBS_FAILS
val can3d: Boolean get() = canControl && supportsDisplayModeControl && !noSignal && sbsSupport != SBS_FAILS
val verticalFovDeg: Float get() {
val half = Math.toRadians(diagonalFovDeg / 2.0)
val aspect = if (width > 0 && height > 0)
@@ -213,7 +214,7 @@ object Glasses {
}
fun sendMode(mode: Int) = post {
if (!_state.value.canControl) return@post
if (!_state.value.canControl || !_state.value.supportsDisplayModeControl) return@post
if (link?.send(VitureProtocol.MSG_DISPLAY, byteArrayOf(mode.toByte())) == true) lastModeSentAt = SystemClock.uptimeMillis()
}
@@ -470,6 +471,7 @@ object Glasses {
.put("controlError", s.controlError ?: JSONObject.NULL)
.put("experimental", s.experimental)
.put("supportsScreen3dof", s.supportsScreen3dof)
.put("supportsDisplayModeControl", s.supportsDisplayModeControl)
.put("supportsSpatial", s.supportsSpatial)
.put("firmware", (link as? VitureSdkLink)?.firmware ?: JSONObject.NULL)
.put("spatialSdk", (link as? VitureSdkLink)?.spatialDiagnostics()?.let {
@@ -614,14 +616,16 @@ object Glasses {
switching3d = modeState.pendingStereo,
brightnessMax = m?.brightnessMax ?: 8, volumeMax = m?.volumeMax ?: 8,
sunblock = if (m === XrealModel) it.sunblock else _settings.value.sunblock ?: it.sunblock,
hardwareControls = device?.vendorId == VitureProtocol.VENDOR_ID || m === XrealModel || m is RokidModel,
hardwareControls = m?.hardwareControls == true &&
(device?.vendorId == VitureProtocol.VENDOR_ID || m === XrealModel || m is RokidModel),
supportsDisplayModeControl = m?.supportsDisplayModeControl == true,
hasSunblock = m?.hasSunblock == true,
diagonalFovDeg = m?.diagonalFovDeg ?: 46f,
tracking = it.tracking && link != null,
noSignal = noSignal,
sbs90 = m?.sbs90 == true,
rates2d = m?.rates2d ?: listOf(60, 90, 120),
experimental = m === XrealModel,
experimental = m === XrealModel || (m is VitureProtocol.Model && m.family == VitureProtocol.Family.PRO2 && !m.needsSdk),
supportsScreen3dof = link?.hasImu == true,
supports30Hz = display?.let(::supports30Hz) == true,
supportsSpatial = (link as? VitureSdkLink)?.isCarina == true,
@@ -653,7 +657,8 @@ object Glasses {
internal fun deviceModel(device: UsbDevice): GlassesModel? {
val name = runCatching { device.productName }.getOrNull()
return if (device.vendorId == VitureProtocol.VENDOR_ID) {
VitureSdk.marketName(device.productId)?.let(VitureProtocol::sdkModel)
if (device.productId == VitureProtocol.PRO2_PRODUCT_ID) VitureProtocol.model(device.productId, name)
else VitureSdk.marketName(device.productId)?.let(VitureProtocol::sdkModel)
?: VitureProtocol.model(device.productId, name)
}
else if (XrealModel.matches(device.vendorId, device.productId)) XrealModel
@@ -720,7 +725,9 @@ object Glasses {
calibrationKey = calibrationStore.key(device.vendorId, device.productId,
runCatching { device.serialNumber }.getOrNull(), model?.name.orEmpty())
val l = if (device.vendorId == VitureProtocol.VENDOR_ID) {
if ((model as? VitureProtocol.Model)?.needsSdk == true) {
if (device.productId == VitureProtocol.PRO2_PRODUCT_ID) {
VitureV2Link.open(usb, device, v2Listener(generation))
} else if ((model as? VitureProtocol.Model)?.needsSdk == true) {
// Android can evict cacheDir while the SDK is running.
Log.i(TAG, "opening VITURE SDK pid=0x%04X spatial=%s".format(device.productId, spatial))
VitureSdkLink.open(usb, device, File(app.noBackupFilesDir, "viture"), sdkListener(generation),
@@ -851,6 +858,40 @@ object Glasses {
}
}
private fun v2Listener(generation: Long) = object : VitureV2Link.Listener {
override fun onReady() = post {
if (generation != linkGeneration) return@post
val current = link as? VitureV2Link ?: return@post
publish { it.copy(connected = current.ready, supportsScreen3dof = current.hasImu,
tracking = current.trackingActive, controlError = null) }
updateImu()
}
override fun onValue(msgId: Int, value: Int) = post {
if (generation != linkGeneration) return@post
when (msgId) {
VitureProtocol.MSG_GET_DISPLAY -> glassesMode = value
VitureProtocol.MSG_GET_BRIGHTNESS -> publish { it.copy(brightness = value) }
VitureProtocol.MSG_GET_VOLUME -> publish { it.copy(volume = value) }
}
}
override fun onPose(raw: ByteArray, q: FloatArray, timeNs: Long) {
if (generation != linkGeneration) return
imuPackets++
probe?.invoke(raw, q)
if (simulating.get() == null) deliver(q, timeNs)
}
override fun onTracking(active: Boolean) = post {
if (generation != linkGeneration) return@post
val current = link as? VitureV2Link ?: return@post
publish { it.copy(tracking = active && current.trackingActive) }
}
override fun onLost() = post {
if (generation != linkGeneration) return@post
closeLink()
publish { it.copy(controlError = app.getString(R.string.glasses_connection_failed)) }
}
}
private fun rayNeoListener(generation: Long) = object : RayNeoLink.Listener {
override fun onDeviceInfo(boardId: Int, calibrationSaved: Boolean) = post {
if (generation != linkGeneration) return@post
@@ -926,7 +967,7 @@ object Glasses {
private fun applyMode(force: Boolean) {
val s = _state.value
val m = model ?: return
if (!s.canControl) return
if (!s.canControl || !s.supportsDisplayModeControl) return
if (modeState.restorePending) {
sendMode(false)
return
@@ -948,6 +989,7 @@ object Glasses {
private fun sendMode(sbs: Boolean): Boolean {
val m = model ?: return false
if (!m.supportsDisplayModeControl) return false
if (sbs && !_settings.value.gameOnGlasses) update { it.copy(gameOnGlasses = true) }
val g = _settings.value
val resolution = GlassesDisplayModes.selected(g, _state.value, sbs)
@@ -980,11 +1022,11 @@ object Glasses {
val l = link ?: return
if (!l.ready) return
val want = (sink != null || poseObservers.isNotEmpty() || probe != null || _calibration.value.running || SpatialTracking.enabled) && l.hasImu
if (want == _state.value.tracking) return
if (l !is VitureV2Link && want == _state.value.tracking) return
val accepted = l.send(VitureProtocol.MSG_IMU, byteArrayOf(if (want) 1 else 0))
if (want && !accepted) return
if (want) l.send(VitureProtocol.MSG_IMU_RATE, byteArrayOf(VitureProtocol.IMU_RATE_240.toByte()))
publish { it.copy(tracking = want) }
publish { it.copy(tracking = if (l is VitureV2Link) l.trackingActive else want) }
}
private fun linkListener(generation: Long) = object : VitureLink.Listener {
@@ -4,6 +4,8 @@ package com.droiddeck.launcher.glasses
interface GlassesModel {
val name: String
val controllable: Boolean
val hardwareControls: Boolean get() = true
val supportsDisplayModeControl: Boolean get() = true
val brightnessMax: Int
val volumeMax: Int
val diagonalFovDeg: Float
@@ -6,6 +6,7 @@ import kotlin.math.sqrt
object VitureProtocol {
const val VENDOR_ID = 0x35CA
const val PRO2_PRODUCT_ID = 0x1301
const val PACKET_SIZE = 64
private const val HEADER = 0x12
@@ -33,13 +34,19 @@ object VitureProtocol {
enum class Family { ONE, PRO, LUMA, ULTRA, BEAST, PRO2 }
class Model(override val name: String, val family: Family) : GlassesModel {
class Model(
override val name: String,
val family: Family,
val needsSdk: Boolean = family == Family.ULTRA || family == Family.BEAST || family == Family.PRO2,
) : GlassesModel {
override val controllable: Boolean get() = true
val needsSdk: Boolean get() = family == Family.ULTRA || family == Family.BEAST || family == Family.PRO2
private val directPro2: Boolean get() = family == Family.PRO2 && !needsSdk
override val hardwareControls: Boolean get() = !directPro2
override val supportsDisplayModeControl: Boolean get() = !directPro2
val tall: Boolean get() = family == Family.LUMA || family == Family.ULTRA || family == Family.BEAST
override val sbs90: Boolean get() = family == Family.ULTRA
override val brightnessMax: Int get() = 8
override val volumeMax: Int get() = if (family == Family.BEAST) 15 else 8
override val brightnessMax: Int get() = if (directPro2) 0 else 8
override val volumeMax: Int get() = if (directPro2) 0 else if (family == Family.BEAST) 15 else 8
override val hasSunblock: Boolean get() = family != Family.PRO2
override val diagonalFovDeg: Float get() = when (family) {
Family.ONE -> 43f
@@ -89,6 +96,7 @@ object VitureProtocol {
}
fun model(productId: Int, productName: String?): Model? {
if (productId == PRO2_PRODUCT_ID) return Model("VITURE Pro 2", Family.PRO2, needsSdk = false)
val family = when (productId) {
0x1011, 0x1013, 0x1015, 0x1017, 0x101b -> Family.ONE
0x1019, 0x101d -> Family.PRO
@@ -0,0 +1,288 @@
package com.droiddeck.launcher.glasses
import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbInterface
import android.hardware.usb.UsbManager
import android.hardware.usb.UsbRequest
import android.util.Log
import java.io.IOException
import java.nio.ByteBuffer
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.TimeoutException
import java.util.concurrent.atomic.AtomicLong
internal class VitureV2Link internal constructor(
private val transport: Transport,
private val listener: Listener,
) : GlassesLink {
interface Listener {
fun onReady()
fun onValue(msgId: Int, value: Int)
fun onPose(raw: ByteArray, q: FloatArray, timeNs: Long)
fun onTracking(active: Boolean)
fun onLost()
}
internal data class Received(val bytes: ByteArray, val timeNs: Long)
internal interface Transport {
fun write(packet: ByteArray): Boolean
fun read(timeoutMs: Long): Received?
fun close()
}
private data class Command(val packet: ByteArray, val stream: Boolean? = null)
private val commands = ArrayBlockingQueue<Command>(16)
private val stateLock = Any()
private val bad = AtomicLong()
@Volatile private var running = true
@Volatile private var wanted = true
@Volatile override var ready = false
private set
@Volatile var trackingActive = false
private set
override val hasImu: Boolean get() = ready
override val badFrames: Long get() = bad.get()
@Volatile private var streamOn = false
private var lastPoseAt = 0L
private var lastTick: Long? = null
private var poseNotBefore = 0L
private val worker = Thread(::run, "viture-v2").apply { isDaemon = true; start() }
override fun send(msgId: Int, payload: ByteArray): Boolean {
synchronized(stateLock) {
if (!running || !ready) return false
if (msgId == VitureProtocol.MSG_IMU) {
if (payload.size != 1 || payload[0].toInt() !in 0..1) return false
val enabled = payload[0].toInt() == 1
if (wanted == enabled) return true
val command = Command(VitureV2Protocol.imuControl(
if (enabled) VitureV2Protocol.STREAM_POSE else VitureV2Protocol.STREAM_OFF), enabled)
if (!commands.offer(command)) return false
wanted = enabled
if (!enabled) {
streamOn = false
tracking(false)
}
return true
}
if (msgId == VitureProtocol.MSG_GET_IMU) return true
// Keep the measured 120 Hz mode; the generic controller requests 240 Hz.
if (msgId == VitureProtocol.MSG_IMU_RATE) return false
val query = when (msgId) {
VitureProtocol.MSG_GET_BRIGHTNESS -> VitureV2Protocol.MSG_GET_BRIGHTNESS
VitureProtocol.MSG_GET_VOLUME -> VitureV2Protocol.MSG_GET_VOLUME
VitureProtocol.MSG_GET_DISPLAY -> VitureV2Protocol.MSG_GET_DISPLAY
else -> return false
}
return payload.isEmpty() && commands.offer(Command(VitureV2Protocol.packet(query)))
}
}
private fun tracking(active: Boolean) {
if (trackingActive != active) {
trackingActive = active
listener.onTracking(active)
}
}
private fun run() {
try {
if (!transport.write(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE)))
throw IOException("Could not start pose stream")
poseNotBefore = System.nanoTime()
streamOn = true
lastPoseAt = System.nanoTime()
while (running) {
commands.poll()?.let { command ->
if (!transport.write(command.packet)) throw IOException("USB command failed")
val completedAt = System.nanoTime()
synchronized(stateLock) {
command.stream?.let {
streamOn = it
lastTick = null
poseNotBefore = completedAt
lastPoseAt = System.nanoTime()
}
}
}
transport.read(100)?.let(::receive)
if (streamOn && System.nanoTime() - lastPoseAt > POSE_TIMEOUT_NS)
throw IOException("No fresh valid pose samples")
}
} catch (e: Exception) {
if (running) {
ready = false
tracking(false)
Log.w(TAG, "V2 connection lost: ${e.message}")
listener.onLost()
}
} finally {
running = false
ready = false
tracking(false)
runCatching { transport.write(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) }
transport.close()
}
}
private fun receive(received: Received) = synchronized(stateLock) {
if (!running) return
val frame = VitureV2Protocol.parse(received.bytes) ?: run { bad.incrementAndGet(); return }
if (frame.msgId == VitureV2Protocol.EVENT_POSE) {
val pose = VitureV2Protocol.pose(frame) ?: run { bad.incrementAndGet(); return }
if (!streamOn || !wanted || received.timeNs < poseNotBefore) return
val previous = lastTick
if (previous != null) {
val delta = (pose.deviceTick - previous) and 0xffffffffL
if (delta == 0L || delta >= 0x80000000L) return
}
lastTick = pose.deviceTick
lastPoseAt = System.nanoTime()
val becameReady = !ready
ready = true
tracking(true)
if (becameReady) listener.onReady()
val q = pose.quaternion
// Upstream right/up/back pose converted to the shared VITURE legacy basis.
val shared = floatArrayOf(-q[2], -q[0], q[1], q[3])
// Upstream does not establish device tick units; use host monotonic receipt time.
if (running && wanted && streamOn) listener.onPose(received.bytes, shared, received.timeNs)
return
}
VitureV2Protocol.reply(frame, VitureV2Protocol.MSG_IMU_CONTROL)?.let {
if (!it.success) throw IOException("Pose stream rejected with status ${it.status}")
}
val queries = arrayOf(
VitureV2Protocol.MSG_GET_BRIGHTNESS to VitureProtocol.MSG_GET_BRIGHTNESS,
VitureV2Protocol.MSG_GET_VOLUME to VitureProtocol.MSG_GET_VOLUME,
VitureV2Protocol.MSG_GET_DISPLAY to VitureProtocol.MSG_GET_DISPLAY,
)
for ((query, internalId) in queries) {
val reply = VitureV2Protocol.reply(frame, query) ?: continue
if (reply.success && reply.body.size == 1) listener.onValue(internalId, reply.body[0].toInt() and 255)
}
}
override fun close() {
synchronized(stateLock) {
running = false
ready = false
wanted = false
commands.clear()
}
if (Thread.currentThread() !== worker) worker.join(1500)
}
companion object {
private const val TAG = "VitureV2Link"
private const val POSE_TIMEOUT_NS = 3_000_000_000L
const val PRODUCT_ID = 0x1301
fun open(usb: UsbManager, device: UsbDevice, listener: Listener): VitureV2Link? {
if (device.vendorId != VitureProtocol.VENDOR_ID || device.productId != PRODUCT_ID) return null
val candidates = (0 until device.interfaceCount).map(device::getInterface).filter {
it.interfaceClass == UsbConstants.USB_CLASS_HID && it.alternateSetting == 0 && it.endpointCount == 2
}.mapNotNull { intf ->
val endpoints = (0 until intf.endpointCount).map(intf::getEndpoint)
val input = endpoints.singleOrNull { it.direction == UsbConstants.USB_DIR_IN &&
it.type == UsbConstants.USB_ENDPOINT_XFER_INT && it.maxPacketSize == 64 }
val output = endpoints.singleOrNull { it.direction == UsbConstants.USB_DIR_OUT &&
it.type == UsbConstants.USB_ENDPOINT_XFER_INT && it.maxPacketSize == 64 }
if (input != null && output != null) Triple(intf, input, output) else null
}
val (intf, input, output) = candidates.singleOrNull() ?: return null
val connection = usb.openDevice(device) ?: return null
if (!connection.claimInterface(intf, true)) { connection.close(); return null }
return try {
VitureV2Link(AndroidTransport(connection, intf, input, output), listener)
} catch (e: Exception) {
connection.releaseInterface(intf)
connection.close()
Log.w(TAG, "Could not initialize USB requests", e)
null
}
}
}
private class AndroidTransport(
private val connection: UsbDeviceConnection,
private val intf: UsbInterface,
input: UsbEndpoint,
output: UsbEndpoint,
) : Transport {
private val inputRequest = UsbRequest()
private val outputRequest = UsbRequest()
private val inputBuffer = ByteBuffer.allocateDirect(64)
private var outputBuffer: ByteBuffer? = null
private var outputPending = false
private val received = ArrayDeque<Received>()
init {
try {
if (!inputRequest.initialize(connection, input) || !outputRequest.initialize(connection, output))
throw IOException("USB request initialization failed")
queueInput()
} catch (e: Exception) {
inputRequest.close()
outputRequest.close()
throw e
}
}
private fun queueInput() {
inputBuffer.clear()
if (!inputRequest.queue(inputBuffer)) throw IOException("USB input queue failed")
}
private fun await(timeoutMs: Long) {
val completed = try { connection.requestWait(timeoutMs) } catch (_: TimeoutException) { return }
?: throw IOException("USB device disconnected")
if (completed === outputRequest) {
outputPending = false
} else if (completed === inputRequest) {
val count = inputBuffer.position()
if (count > 0) {
val bytes = ByteArray(count)
inputBuffer.flip()
inputBuffer.get(bytes)
if (received.size >= 512) throw IOException("USB input backlog overflow")
received.addLast(Received(bytes, System.nanoTime()))
}
queueInput()
}
}
override fun write(packet: ByteArray): Boolean {
if (outputPending) throw IOException("Previous USB output has not completed")
val buffer = ByteBuffer.allocateDirect(packet.size).apply { put(packet); flip() }
outputBuffer = buffer
outputPending = outputRequest.queue(buffer)
if (!outputPending) return false
val deadline = System.nanoTime() + 250_000_000L
while (outputPending && System.nanoTime() < deadline) await(25)
if (outputPending) {
outputRequest.cancel()
throw IOException("USB output timed out")
}
return buffer.position() == packet.size
}
override fun read(timeoutMs: Long): Received? {
if (received.isEmpty()) await(timeoutMs)
return received.removeFirstOrNull()
}
override fun close() {
inputRequest.cancel()
if (outputPending) outputRequest.cancel()
connection.releaseInterface(intf)
connection.close()
inputRequest.close()
outputRequest.close()
outputBuffer = null
}
}
}
@@ -0,0 +1,132 @@
// Adapted from elasticjava/viture-v2, MIT, Copyright (c) 2026 Holger Bartnick.
// Source: ece8c30485f7d357fefa362ae74f3eabac9b3899; see docs/third-party/viture-v2/.
package com.droiddeck.launcher.glasses
import kotlin.math.sqrt
object VitureV2Protocol {
const val PACKET_SIZE = 64
const val HEADER_SIZE = 8
const val RESPONSE_OFFSET = 0x2000
private const val PREAMBLE = 0x0010
private const val MAX_PAYLOAD_SIZE = PACKET_SIZE - HEADER_SIZE
const val MSG_IMU_CONTROL = 0x0301
const val MSG_GET_SERIAL = 0x3002
const val MSG_GET_VERSION = 0x3003
const val MSG_GET_BRIGHTNESS = 0x3122
const val MSG_GET_DUTY_CYCLE = 0x3125
const val MSG_GET_DISPLAY = 0x3141
const val MSG_GET_VOLUME = 0x3201
const val MSG_GET_WEAR = 0x3321
const val EVENT_POSE = 0x7308
const val EVENT_RAW = 0x7309
const val STREAM_OFF = 0
const val STREAM_POSE = 1
const val STREAM_RAW = 2
enum class Rate(val wireValue: Int, val hz: Int) {
HZ_60(0, 60), HZ_90(1, 90), HZ_120(2, 120),
HZ_240(3, 240), HZ_500(4, 500), HZ_1000(5, 1000),
}
class Frame internal constructor(val msgId: Int, val payload: ByteArray)
class Reply internal constructor(val status: Int, val body: ByteArray) {
val success: Boolean get() = status == 0
}
// Device ticks have no established time unit; quaternion is xyzw with no axis remapping.
class Pose internal constructor(
val deviceTick: Long,
val quaternion: FloatArray,
val unknown: Long,
)
class RawSample internal constructor(
val deviceTick: Long,
val gyroRadPerSec: FloatArray,
val accelG: FloatArray,
val payload: ByteArray,
)
fun packet(msgId: Int, payload: ByteArray = ByteArray(0)): ByteArray {
require(msgId in 0..0xFFFF)
require(payload.size <= MAX_PAYLOAD_SIZE)
return ByteArray(HEADER_SIZE + payload.size).also { buffer ->
putU16(buffer, 0, PREAMBLE)
putU16(buffer, 2, msgId)
putU16(buffer, 4, payload.size)
putU16(buffer, 6, checksum(payload, 0, payload.size))
payload.copyInto(buffer, HEADER_SIZE)
}
}
fun imuControl(streams: Int, rate: Rate = Rate.HZ_120): ByteArray {
// Upstream measured that stream mask 3 ACKs but produces no events on Pro 2.
require(streams == STREAM_OFF || streams == STREAM_POSE || streams == STREAM_RAW)
require(streams != STREAM_POSE || rate.hz <= 240)
val wireRate = if (streams == STREAM_OFF) 0 else rate.wireValue
return packet(MSG_IMU_CONTROL, byteArrayOf(streams.toByte(), wireRate.toByte()))
}
fun parse(buffer: ByteArray, size: Int = buffer.size): Frame? {
if (size < HEADER_SIZE || size > PACKET_SIZE || size > buffer.size) return null
if (u16(buffer, 0) != PREAMBLE) return null
val payloadSize = u16(buffer, 4)
if (payloadSize > MAX_PAYLOAD_SIZE || HEADER_SIZE + payloadSize > size) return null
if (checksum(buffer, HEADER_SIZE, payloadSize) != u16(buffer, 6)) return null
return Frame(u16(buffer, 2), buffer.copyOfRange(HEADER_SIZE, HEADER_SIZE + payloadSize))
}
fun reply(frame: Frame, requestMsgId: Int): Reply? {
if (requestMsgId !in 0..0xFFFF || frame.msgId != ((requestMsgId + RESPONSE_OFFSET) and 0xFFFF)) return null
if (frame.payload.isEmpty()) return null
return Reply(u8(frame.payload[0]), frame.payload.copyOfRange(1, frame.payload.size))
}
fun pose(frame: Frame): Pose? {
if (frame.msgId != EVENT_POSE || frame.payload.size != 24) return null
val payload = frame.payload
val w = float(payload, 8)
val x = float(payload, 12)
val y = float(payload, 16)
val z = float(payload, 20)
if (!w.isFinite() || !x.isFinite() || !y.isFinite() || !z.isFinite()) return null
val norm = sqrt(w.toDouble() * w + x.toDouble() * x + y.toDouble() * y + z.toDouble() * z)
if (norm !in 0.9..1.1) return null
val n = norm.toFloat()
return Pose(u32(payload, 4), floatArrayOf(x / n, y / n, z / n, w / n), u32(payload, 0))
}
fun raw(frame: Frame): RawSample? {
if (frame.msgId != EVENT_RAW || frame.payload.size != 56) return null
val payload = frame.payload
val gyro = floatArrayOf(float(payload, 10), float(payload, 14), float(payload, 18))
val accel = floatArrayOf(float(payload, 22), float(payload, 26), float(payload, 30))
if (gyro.any { !it.isFinite() } || accel.any { !it.isFinite() }) return null
return RawSample(u32(payload, 4), gyro, accel, payload.copyOf())
}
private fun checksum(buffer: ByteArray, offset: Int, size: Int): Int {
var sum = 0
for (i in offset until offset + size) sum += u8(buffer[i])
return sum and 0xFFFF
}
private fun u8(value: Byte) = value.toInt() and 0xFF
private fun u16(buffer: ByteArray, offset: Int) =
u8(buffer[offset]) or (u8(buffer[offset + 1]) shl 8)
private fun u32(buffer: ByteArray, offset: Int): Long =
u16(buffer, offset).toLong() or (u16(buffer, offset + 2).toLong() shl 16)
private fun float(buffer: ByteArray, offset: Int): Float = Float.fromBits(u32(buffer, offset).toInt())
private fun putU16(buffer: ByteArray, offset: Int, value: Int) {
buffer[offset] = value.toByte()
buffer[offset + 1] = (value ushr 8).toByte()
}
}
@@ -57,10 +57,11 @@ object DeviceInfo {
add("Model found from", when (gpu.modelSource) {
"kernel" -> "the kernel's GPU name"
"vulkan" -> "the Vulkan driver (the kernel's name has no model)"
"platform" -> "the platform (the kernel's name has no model)"
"platform" -> "the platform or SoC (the kernel and Vulkan names have no model)"
else -> "unknown"
})
add("Kernel name", gpu.kgslName)
add("Kernel chip id", gpu.kgslChipId)
val kgsl = "/sys/class/kgsl/kgsl-3d0"
add("Clock range", gpuRange())
add("Load", read("$kgsl/gpu_busy_percentage")?.let { if (it.endsWith("%")) it else "$it %" })
@@ -14,6 +14,8 @@ data class GpuInfo(
val oneUi8Gen2: Boolean,
val kgslName: String = "",
val modelSource: String = "",
val kgslChipId: String = "",
val platformGpuModel: Int = 0,
) {
enum class Family(val label: String) {
A8XX("Adreno 8xx"),
@@ -28,9 +30,12 @@ data class GpuInfo(
enum class Support { TESTED, UNTESTED, UNSUPPORTED }
private val isA850: Boolean get() = model == 850 || platformGpuModel == 850
val support: Support
get() = when {
family == Family.NOT_ADRENO -> Support.UNSUPPORTED
isA850 -> Support.UNTESTED
family == Family.A6XX && model == 650 -> Support.TESTED
family == Family.A8XX -> Support.TESTED
family == Family.A7XX && model >= 725 -> Support.TESTED
@@ -40,14 +45,19 @@ data class GpuInfo(
val supportText: String
get() = when (support) {
Support.TESTED -> "Supported"
Support.UNTESTED -> if (family == Family.A7XX_LOW) "Experimental: its drivers are test builds"
Support.UNTESTED -> if (isA850) "Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device"
else if (family == Family.A7XX_LOW) "Experimental: its drivers are test builds"
else "Outside tested hardware (Adreno 650, 725 and newer): it may not run"
Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
}
fun supportText(context: Context): String = context.getString(when (support) {
Support.TESTED -> R.string.gpuinfo_supported
Support.UNTESTED -> if (family == Family.A7XX_LOW) R.string.gpuinfo_experimental else R.string.gpuinfo_below_tested
Support.UNTESTED -> when {
isA850 -> R.string.gpuinfo_a850_experimental
family == Family.A7XX_LOW -> R.string.gpuinfo_experimental
else -> R.string.gpuinfo_below_tested
}
Support.UNSUPPORTED -> R.string.gpuinfo_unsupported
})
@@ -58,38 +68,49 @@ data class GpuInfo(
fun detect(): GpuInfo {
val adreno = File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
val raw = listOf("/sys/class/kgsl/kgsl-3d0/gpu_model", "/sys/class/kgsl/kgsl-3d0/gpu_chipid")
.firstNotNullOfOrNull { FileUtils.readString(File(it))?.trim()?.takeIf(String::isNotEmpty) }
val raw = FileUtils.readString(File("/sys/class/kgsl/kgsl-3d0/gpu_model"))?.trim()
val chipId = FileUtils.readString(File("/sys/class/kgsl/kgsl-3d0/gpu_chipid"))?.trim().orEmpty()
val soc = if (adreno) SocNames.label() else ""
val fromKernel = raw?.let { threeDigits(it) } ?: 0
val fromVulkan = if (fromKernel > 0 || !adreno) 0 else VulkanInfo.cachedOrNull()?.get("device")?.let { threeDigits(it) } ?: 0
val fromPlatform = if (fromKernel > 0 || fromVulkan > 0 || !adreno) 0 else platformModel()
val model = maxOf(fromKernel, fromVulkan, fromPlatform)
val source = when {
fromKernel > 0 -> "kernel"
fromVulkan > 0 -> "vulkan"
fromPlatform > 0 -> "platform"
else -> ""
}
val platformGpuModel = if (adreno) platformModel() else 0
val (model, source) = if (adreno) modelFromNames(
raw,
{ VulkanInfo.cachedOrNull()?.get("device") },
{ platformGpuModel },
) else 0 to ""
val family = familyOf(adreno, model)
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
return GpuInfo(
name = if (!adreno) Build.HARDWARE.ifBlank { UNNAMED } else if (model > 0) "Adreno $model" else "Adreno",
model = model, family = family, soc = soc,
oneUi8Gen2 = samsung && model == 740,
kgslName = raw.orEmpty(), modelSource = source,
kgslName = raw.orEmpty(), modelSource = source, kgslChipId = chipId,
platformGpuModel = platformGpuModel,
)
}
internal fun threeDigits(text: String): Int = Regex("""(\d{3})""").find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
internal fun threeDigits(text: String): Int = Regex("""(?i)\badreno\s*(?:\(TM\)\s*)?(\d{3})(?!\d)""").find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
internal fun modelFromNames(
kernelName: String?,
vulkanName: () -> String?,
fallback: () -> Int,
): Pair<Int, String> {
kernelName?.let { threeDigits(it) }?.takeIf { it > 0 }?.let { return it to "kernel" }
vulkanName()?.let { threeDigits(it) }?.takeIf { it > 0 }?.let { return it to "vulkan" }
return fallback().let { if (it > 0) it to "platform" else 0 to "" }
}
private val PLATFORMS = mapOf(
"msmnile" to 640, "kona" to 650, "lahaina" to 660, "taro" to 730, "cape" to 730,
"kalama" to 740, "pineapple" to 750, "sun" to 830,
)
internal fun platformModel(platform: String = systemProperty("ro.board.platform")): Int =
PLATFORMS[platform.lowercase()] ?: PLATFORMS[systemProperty("ro.vendor.qti.soc_name").lowercase()] ?: 0
internal fun platformModel(
platform: String = systemProperty("ro.board.platform"),
qtiSocName: String = systemProperty("ro.vendor.qti.soc_name"),
socModel: String = SocNames.model(),
): Int = if (SocNames.normalizedModel(socModel) == "SM8975" || SocNames.normalizedModel(qtiSocName) == "SM8975") 850
else PLATFORMS[platform.lowercase()] ?: PLATFORMS[qtiSocName.lowercase()] ?: 0
fun systemProperty(name: String): String = try {
Class.forName("android.os.SystemProperties").getMethod("get", String::class.java).invoke(null, name) as? String ?: ""
@@ -8,6 +8,7 @@ object SocNames {
"SM8350" to "Snapdragon 888", "SM8450" to "Snapdragon 8 Gen 1", "SM8475" to "Snapdragon 8+ Gen 1",
"SM8550" to "Snapdragon 8 Gen 2", "QCS8550" to "Snapdragon 8 Gen 2", "SM8650" to "Snapdragon 8 Gen 3",
"SM8750" to "Snapdragon 8 Elite", "SM8850" to "Snapdragon 8 Elite Gen 5",
"SM8975" to "Snapdragon 8 Elite Extreme Gen 6",
"SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3",
"SM6375" to "Snapdragon 695",
)
@@ -25,8 +26,10 @@ object SocNames {
.firstOrNull { it.isNotEmpty() && !Regex("(?i)^msm_\\d").containsMatchIn(it) }.orEmpty()
}
internal fun normalizedModel(model: String): String = model.trim().uppercase().removePrefix("QTI ").trim()
fun name(model: String, platform: String = GpuInfo.systemProperty("ro.board.platform")): String? =
MODELS[model.uppercase()] ?: PLATFORMS[platform.lowercase()]?.let { "$it family" }
MODELS[normalizedModel(model)] ?: PLATFORMS[platform.lowercase()]?.let { "$it family" }
fun label(model: String = model(), platform: String = GpuInfo.systemProperty("ro.board.platform")): String {
val name = name(model, platform)
@@ -284,27 +284,15 @@ public final class TurnipDriver {
}
String quest = QuestExperimental.INSTANCE.defaultAndroidDriver();
if (quest != null) return quest;
String model = gpuModel();
Log.i(TAG, "gpu model: " + (model == null ? "unknown" : model));
if (model != null) {
java.util.regex.Matcher m = java.util.regex.Pattern.compile("(\\d)\\d\\d").matcher(model);
if (m.find()) {
char generation = m.group(1).charAt(0);
if (generation >= '8') return DRIVER_A8XX;
if (generation == '7') return DRIVER_A7XX;
if (generation == '6') return DRIVER_A6XX;
}
}
return android.os.Build.VERSION.SDK_INT >= 36 ? DRIVER_A8XX : DRIVER_A7XX;
int model = GpuInfo.Companion.detect().getModel();
Log.i(TAG, "gpu model: " + (model == 0 ? "unknown" : model));
return chooseByModel(model, android.os.Build.VERSION.SDK_INT);
}
private static String gpuModel() {
for (String path : new String[]{
"/sys/class/kgsl/kgsl-3d0/gpu_model",
"/sys/class/kgsl/kgsl-3d0/gpu_chipid"}) {
String value = FileUtils.readString(new File(path));
if (value != null && !value.trim().isEmpty()) return value.trim();
}
return null;
static String chooseByModel(int model, int sdk) {
if (model >= 800) return DRIVER_A8XX;
if (model >= 700) return DRIVER_A7XX;
if (model >= 600) return DRIVER_A6XX;
return sdk >= 36 ? DRIVER_A8XX : DRIVER_A7XX;
}
}
@@ -44,6 +44,19 @@ object SessionDisplay {
fun unfoldedGameHeight(width: Int, height: Int): Int =
minOf(width * 9 / 16, (height * UNFOLDED_MAX_GAME_SHARE).toInt()) and 1.inv()
fun unfoldedControlsWanted(
enabled: Boolean,
foldable: Boolean,
controllerConnected: Boolean,
keepWithController: Boolean,
steamDeckPad: Boolean,
pip: Boolean,
width: Int,
height: Int,
smallestWidthDp: Int,
): Boolean = enabled && foldable && (keepWithController || !controllerConnected) && steamDeckPad &&
!pip && width > 0 && height > 0 && smallestWidthDp >= UNFOLDED_MIN_DP
fun panelSize(context: Context): Pair<Int, Int> {
val manager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
@@ -222,6 +222,7 @@ object SessionFiles {
if (!FileUtils.writeString(File(etc, "steam-compatibility-label"), context.getString(R.string.steam_compat_label))) {
Log.e(TAG, "could not write steam-compatibility-label")
}
writeCjkFontConfig(root, etc)
val droiddeckEtc = File(etc, "droiddeck").apply { mkdirs() }
val stagedSocket = File(droiddeckEtc, "bwrap-socket.staged")
if (!FileUtils.writeString(stagedSocket, BwrapSpawner.socket(context) + "\n")
@@ -563,4 +564,96 @@ object SessionFiles {
).joinToString(newline)
fun logDirectory(context: Context): File = LinuxRuntime.logDir(context).apply { mkdirs() }
/**
* Registers the Android system fonts (which include CJK faces such as Noto Sans CJK /
* MiSans) with the container's fontconfig, so the Steam Deck UI (CEF/webkit renderer)
* resolves Chinese/Japanese glyphs instead of showing tofu / mojibake.
* The fonts themselves are bind-mounted by LinuxRuntime.bindSystemFonts() into
* /usr/local/share/fonts/android; here we only need to point fontconfig at them.
*/
private fun writeCjkFontConfig(root: File, etc: File) {
try {
val confDir = File(etc, "fonts/conf.d").apply { mkdirs() }
val conf = File(confDir, "99-droiddeck-cjk.conf")
val xml = """<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
<dir>/usr/local/share/fonts/android</dir>
<dir>/system/fonts</dir>
<match target="pattern">
<test name="lang" compare="contains"><string>ja</string></test>
<test name="family" qual="any"><string>sans-serif</string></test>
<edit name="family" mode="prepend" binding="strong"><string>Noto Sans CJK JP</string></edit>
</match>
<match target="pattern">
<test name="lang" compare="contains"><string>ja</string></test>
<test name="family" qual="any"><string>serif</string></test>
<edit name="family" mode="prepend" binding="strong"><string>Noto Serif CJK JP</string></edit>
</match>
<match target="pattern">
<test name="lang" compare="eq"><string>zh</string></test>
<test name="family" qual="any"><string>sans-serif</string></test>
<edit name="family" mode="prepend" binding="strong"><string>Noto Sans CJK SC</string></edit>
</match>
<match target="pattern">
<test name="lang" compare="eq"><string>zh</string></test>
<test name="family" qual="any"><string>serif</string></test>
<edit name="family" mode="prepend" binding="strong"><string>Noto Serif CJK SC</string></edit>
</match>
<match target="pattern">
<test name="lang" compare="eq"><string>zh-cn</string></test>
<test name="family" qual="any"><string>sans-serif</string></test>
<edit name="family" mode="prepend" binding="strong"><string>Noto Sans CJK SC</string></edit>
</match>
<match target="pattern">
<test name="lang" compare="eq"><string>zh-cn</string></test>
<test name="family" qual="any"><string>serif</string></test>
<edit name="family" mode="prepend" binding="strong"><string>Noto Serif CJK SC</string></edit>
</match>
<match target="pattern">
<test name="lang" compare="eq"><string>zh-tw</string></test>
<test name="family" qual="any"><string>sans-serif</string></test>
<edit name="family" mode="prepend" binding="strong"><string>Noto Sans CJK TC</string></edit>
</match>
<match target="pattern">
<test name="lang" compare="eq"><string>zh-tw</string></test>
<test name="family" qual="any"><string>serif</string></test>
<edit name="family" mode="prepend" binding="strong"><string>Noto Serif CJK TC</string></edit>
</match>
<match target="pattern">
<test name="lang" compare="eq"><string>zh-hk</string></test>
<test name="family" qual="any"><string>sans-serif</string></test>
<edit name="family" mode="prepend" binding="strong"><string>Noto Sans CJK TC</string></edit>
</match>
<match target="pattern">
<test name="lang" compare="eq"><string>zh-hk</string></test>
<test name="family" qual="any"><string>serif</string></test>
<edit name="family" mode="prepend" binding="strong"><string>Noto Serif CJK TC</string></edit>
</match>
<match target="pattern">
<test name="lang" compare="contains"><string>ko</string></test>
<test name="family" qual="any"><string>sans-serif</string></test>
<edit name="family" mode="prepend" binding="strong"><string>Noto Sans CJK KR</string></edit>
</match>
<match target="pattern">
<test name="lang" compare="contains"><string>ko</string></test>
<test name="family" qual="any"><string>serif</string></test>
<edit name="family" mode="prepend" binding="strong"><string>Noto Serif CJK KR</string></edit>
</match>
</fontconfig>
"""
if (!conf.isFile || FileUtils.readString(conf) != xml) {
val staged = File(confDir, conf.name + ".staged")
if (FileUtils.writeString(staged, xml) && staged.renameTo(conf)) {
Log.i(TAG, "Wrote CJK fontconfig 99-droiddeck-cjk.conf")
} else {
staged.delete()
Log.e(TAG, "Could not write CJK fontconfig")
}
}
} catch (e: Exception) {
Log.w(TAG, "CJK fontconfig setup failed", e)
}
}
}
@@ -759,6 +759,16 @@ object SessionPrefs {
prefs(context).edit().putString("theme", id).apply()
}
/** The custom Gradient theme's primary and secondary colours (ARGB). */
fun gradientColors(context: Context): Pair<Int, Int> = prefs(context).let {
it.getInt("gradientPrimary", com.droiddeck.launcher.ui.Themes.DEFAULT_PRIMARY) to
it.getInt("gradientSecondary", com.droiddeck.launcher.ui.Themes.DEFAULT_SECONDARY)
}
fun setGradientColors(context: Context, primary: Int, secondary: Int) {
prefs(context).edit().putInt("gradientPrimary", primary).putInt("gradientSecondary", secondary).apply()
}
private fun customResolution(context: Context, mode: String): Pair<Int, Int>? =
parseResolution(prefs(context).getString("customRes.$mode", null))
@@ -979,6 +989,13 @@ object SessionPrefs {
prefs(context).edit().putBoolean("unfoldedControls", enabled).apply()
}
fun unfoldedControlsWithController(context: Context): Boolean =
prefs(context).getBoolean("unfoldedControlsWithController", false)
fun setUnfoldedControlsWithController(context: Context, enabled: Boolean) {
prefs(context).edit().putBoolean("unfoldedControlsWithController", enabled).apply()
}
const val SURFACE_STICK = "stick"
const val SURFACE_TRACKPAD = "trackpad"
@@ -76,9 +76,16 @@ class SessionService : Service() {
private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL
private var steamDownloadsInBackground = false
private var activityVisible = true
private var activityDisplayId = Display.DEFAULT_DISPLAY
private var xrActivityVisible = false
private var signInHold = false
private val hasVisibleSurface get() = sessionHasVisibleSurface(activityVisible || signInHold, screenOn, xrActivityVisible)
private val hasVisibleSurface get() = !SessionVisibilityPolicy.isHidden(
activityStarted = activityVisible || signInHold,
defaultDisplayOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn,
activityOnDefaultDisplay = activityDisplayId == Display.DEFAULT_DISPLAY,
activityDisplayOn = activityDisplayOn(),
xrActivityVisible = xrActivityVisible,
)
private var screenOn = true
private var sessionDisplayId = Display.DEFAULT_DISPLAY
private var manualPauseRequested = false
@@ -115,12 +122,22 @@ class SessionService : Service() {
private val displayListener = object : DisplayManager.DisplayListener {
override fun onDisplayAdded(displayId: Int) {}
override fun onDisplayRemoved(displayId: Int) {
if (displayId != sessionDisplayId) return
sessionDisplayId = Display.DEFAULT_DISPLAY
refreshScreenOn()
if (displayId == sessionDisplayId) {
sessionDisplayId = Display.DEFAULT_DISPLAY
refreshScreenOn()
}
if (displayId == activityDisplayId) {
suspendAttemptFailed = false
updateSuspendPolicy()
}
}
override fun onDisplayChanged(displayId: Int) {
if (displayId == sessionDisplayId && displayId != Display.DEFAULT_DISPLAY) refreshScreenOn()
if (displayId == activityDisplayId) {
resumeSteamSleepOnReturn()
suspendAttemptFailed = false
updateSuspendPolicy()
}
}
}
@@ -132,6 +149,14 @@ class SessionService : Service() {
interactive ?: (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: true, state)
}
private fun activityDisplayOn(): Boolean {
if (activityDisplayId == Display.DEFAULT_DISPLAY) {
return (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn
}
val displays = getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager ?: return false
return displays.getDisplay(activityDisplayId)?.state == Display.STATE_ON
}
private fun refreshScreenOn() {
val on = readScreenOn()
if (on == screenOn) return
@@ -202,6 +227,7 @@ class SessionService : Service() {
ACTION_ACTIVITY_VISIBLE -> {
if (!SessionState.pipActive) pipTask = false
activityVisible = true
activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId)
sessionDisplayId = intent.getIntExtra(EXTRA_DISPLAY_ID, sessionDisplayId)
screenOn = readScreenOn()
suspendDownloadNow = false
@@ -215,8 +241,16 @@ class SessionService : Service() {
refreshScreenOn()
return START_NOT_STICKY
}
ACTION_ACTIVITY_DISPLAY_CHANGED -> {
activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId)
resumeSteamSleepOnReturn()
suspendAttemptFailed = false
updateSuspendPolicy()
return START_NOT_STICKY
}
ACTION_ACTIVITY_HIDDEN -> {
activityVisible = false
activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId)
suspendAttemptFailed = false
updateSuspendPolicy()
return START_NOT_STICKY
@@ -279,6 +313,7 @@ class SessionService : Service() {
xrActivityVisible = false
signInHold = false
sessionDisplayId = intent?.getIntExtra(EXTRA_DISPLAY_ID, Display.DEFAULT_DISPLAY) ?: Display.DEFAULT_DISPLAY
activityDisplayId = intent?.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, sessionDisplayId) ?: sessionDisplayId
screenOn = readScreenOn()
manualPauseRequested = false
suspendDownloadNow = false
@@ -1842,7 +1877,9 @@ class SessionService : Service() {
private const val ACTION_ACTIVITY_VISIBLE = "com.droiddeck.launcher.ACTIVITY_VISIBLE"
private const val ACTION_ACTIVITY_HIDDEN = "com.droiddeck.launcher.ACTIVITY_HIDDEN"
private const val ACTION_ACTIVITY_DISPLAY = "com.droiddeck.launcher.ACTIVITY_DISPLAY"
private const val ACTION_ACTIVITY_DISPLAY_CHANGED = "com.droiddeck.launcher.ACTIVITY_DISPLAY_CHANGED"
private const val EXTRA_DISPLAY_ID = "displayId"
private const val EXTRA_ACTIVITY_DISPLAY_ID = "activityDisplayId"
private const val ACTION_XR_ACTIVITY_VISIBLE = "com.droiddeck.launcher.XR_ACTIVITY_VISIBLE"
private const val ACTION_XR_ACTIVITY_HIDDEN = "com.droiddeck.launcher.XR_ACTIVITY_HIDDEN"
private const val ACTION_SIGN_IN_HOLD = "com.droiddeck.launcher.SIGN_IN_HOLD"
@@ -1887,8 +1924,10 @@ class SessionService : Service() {
steamUi: String? = null, steamUrl: String? = null, programArgs: Array<String>? = null,
displayId: Int = Display.DEFAULT_DISPLAY,
) {
SessionState.activityDisplayId = displayId
val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode)
.putExtra(EXTRA_DISPLAY_ID, displayId)
.putExtra(EXTRA_ACTIVITY_DISPLAY_ID, displayId)
if (program != null) intent.putExtra(EXTRA_PROGRAM, program)
if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs)
if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi)
@@ -1909,15 +1948,29 @@ class SessionService : Service() {
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_PIP_BEGIN))
}
fun setActivityVisible(context: Context, visible: Boolean, displayId: Int = Display.DEFAULT_DISPLAY) {
fun setActivityVisible(context: Context, visible: Boolean, displayId: Int = contextDisplayId(context)) {
if (!SessionState.running) return
val action = if (visible) ACTION_ACTIVITY_VISIBLE else ACTION_ACTIVITY_HIDDEN
context.startService(Intent(context, SessionService::class.java).setAction(action).putExtra(EXTRA_DISPLAY_ID, displayId))
SessionState.activityDisplayId = displayId
context.startService(Intent(context, SessionService::class.java).setAction(action)
.putExtra(EXTRA_DISPLAY_ID, displayId)
.putExtra(EXTRA_ACTIVITY_DISPLAY_ID, displayId))
}
fun setActivityDisplay(context: Context, displayId: Int) {
if (!SessionState.running) return
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_ACTIVITY_DISPLAY).putExtra(EXTRA_DISPLAY_ID, displayId))
SessionState.activityDisplayId = displayId
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_ACTIVITY_DISPLAY)
.putExtra(EXTRA_DISPLAY_ID, displayId))
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_ACTIVITY_DISPLAY_CHANGED)
.putExtra(EXTRA_ACTIVITY_DISPLAY_ID, displayId))
}
@Suppress("DEPRECATION")
private fun contextDisplayId(context: Context): Int {
val activity = context as? android.app.Activity ?: return Display.DEFAULT_DISPLAY
return if (Build.VERSION.SDK_INT >= 30) activity.display?.displayId ?: activity.windowManager.defaultDisplay.displayId
else activity.windowManager.defaultDisplay.displayId
}
fun setXrActivityVisible(context: Context, visible: Boolean) {
@@ -42,6 +42,8 @@ object SessionState {
@Volatile
var running = false
@Volatile
var activityDisplayId = 0
@Volatile
var runtimeDriver: String? = null
var suspended by mutableStateOf(false)
@Volatile var pipActive = false
@@ -0,0 +1,15 @@
package com.droiddeck.launcher.session
internal object SessionVisibilityPolicy {
fun isHidden(
activityStarted: Boolean,
defaultDisplayOn: Boolean,
activityOnDefaultDisplay: Boolean,
activityDisplayOn: Boolean,
xrActivityVisible: Boolean = false,
): Boolean = !sessionHasVisibleSurface(
panelVisible = activityStarted,
screenOn = if (activityOnDefaultDisplay) defaultDisplayOn else activityDisplayOn,
xrVisible = xrActivityVisible,
)
}
@@ -15,7 +15,8 @@ object SettingsReset {
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "touch", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "stretch16x9", "picturePosition",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
@@ -23,6 +23,8 @@ import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
@@ -493,7 +495,7 @@ private fun IconSuggestions(repo: String, selected: String?, onPick: (String) ->
if (list != null && list.isEmpty()) return
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.height(44.dp)) {
Small(stringResource(if (list == null) R.string.add_app_icon_searching else R.string.add_app_icon_suggestions))
if (list != null) Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) {
if (list != null) Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState()).selectableGroup()) {
list.forEachIndexed { i, url -> Rise(i) { SuggestedIcon(url, url == selected) { onPick(url) } } }
}
}
@@ -510,7 +512,7 @@ private fun SuggestedIcon(url: String, selected: Boolean, onClick: () -> Unit) {
contentAlignment = Alignment.Center,
modifier = Modifier.size(44.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(colors.surface)
.glideBorder(hot, Shape12, pal.signal, pal.line2)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.hoverable(src).selectable(selected = selected, role = androidx.compose.ui.semantics.Role.RadioButton, interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick),
) {
AsyncImage(model = ImageRequest.Builder(LocalContext.current).data(url).crossfade(true).build(), contentDescription = stringResource(R.string.add_app_icon), contentScale = ContentScale.Fit, modifier = Modifier.size(34.dp))
@@ -0,0 +1,141 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import kotlin.math.atan2
import kotlin.math.hypot
import kotlin.math.min
/** A small colour square; pressing it opens the colour picker. */
@Composable
internal fun ColorCube(color: Color, description: String, focus: FocusRequester? = null, onClick: () -> Unit) {
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(10.dp)
Box(
Modifier.then(if (focus != null) Modifier.focusRequester(focus) else Modifier).size(44.dp).clip(shape).background(color)
.border(1.dp, pal.line2, shape).glideBorder(hot, shape, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.semantics { contentDescription = description },
)
}
/** Colour wheel (touch), hue / saturation / brightness sliders (controller and touch) and a hex box for one colour. */
@Composable
internal fun ColorPickerDialog(title: String, initial: Int, onDismiss: () -> Unit, onApply: (Int) -> Unit) {
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
val start = remember { ThemeColors.toHsv(initial) }
var hue by remember { mutableStateOf(start.h) }
var sat by remember { mutableStateOf(start.s) }
var value by remember { mutableStateOf(start.v) }
var hexText by remember { mutableStateOf(ThemeColors.hex(initial)) }
val current = ThemeColors.fromHsv(hue, sat, value)
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { focusSoon { first } }
fun picked(h: Float = hue, s: Float = sat, v: Float = value) {
hue = h.coerceIn(0f, 360f); sat = s.coerceIn(0f, 1f); value = v.coerceIn(0f, 1f)
hexText = ThemeColors.hex(ThemeColors.fromHsv(hue, sat, value))
}
AppDialog(shown, close, "colorPicker", wide = false, maxWidth = 460.dp) {
DialogTitleRow(title, close)
Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
ColorWheel(hue, sat, value) { h, s -> picked(h = h, s = s) }
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Swatch(Color(initial))
Swatch(Color(current))
}
}
ValueSlider(hue.toInt(), 0..360, step = 5, enabled = true, label = stringResource(R.string.theme_color_hue), format = { "$it°" },
modifier = Modifier.focusRequester(first)) { picked(h = it.toFloat()) }
ValueSlider((sat * 100).toInt(), 0..100, step = 2, enabled = true, label = stringResource(R.string.theme_color_saturation), format = { "$it%" }) { picked(s = it / 100f) }
ValueSlider((value * 100).toInt(), 0..100, step = 2, enabled = true, label = stringResource(R.string.theme_color_brightness), format = { "$it%" }) { picked(v = it / 100f) }
AdbTextField(
value = hexText,
onValueChange = { text ->
hexText = text
ThemeColors.parseHex(text)?.let { argb -> ThemeColors.toHsv(argb).let { hsv -> hue = hsv.h; sat = hsv.s; value = hsv.v } }
},
label = "", keyboardType = KeyboardType.Ascii, imeAction = ImeAction.Done, placeholder = stringResource(R.string.theme_color_hex),
onDone = { ThemeColors.parseHex(hexText)?.let { onApply(it); close() } },
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
SecondaryButton(stringResource(R.string.common_cancel), modifier = Modifier.weight(1f), onClick = close)
PrimaryButton(stringResource(R.string.common_ok), enabled = ThemeColors.parseHex(hexText) != null, modifier = Modifier.weight(1f)) {
ThemeColors.parseHex(hexText)?.let { onApply(it); close() }
}
}
}
}
@Composable
private fun Swatch(color: Color) {
val shape = RoundedCornerShape(10.dp)
Box(Modifier.size(48.dp).clip(shape).background(color).border(1.dp, LocalPalette.current.line2, shape))
}
/** Hue around the circle and saturation out from the middle, at full brightness; brightness has its own slider. */
@Composable
private fun ColorWheel(hue: Float, sat: Float, value: Float, onPick: (hue: Float, sat: Float) -> Unit) {
val rim = MaterialTheme.colorScheme.onBackground
val size = 168.dp
fun at(offset: Offset, side: Float) {
val center = side / 2f
val dx = offset.x - center
val dy = offset.y - center
val angle = Math.toDegrees(atan2(dy, dx).toDouble()).toFloat()
onPick((angle + 360f) % 360f, min(1f, hypot(dx, dy) / center))
}
Canvas(
Modifier.size(size)
.pointerInput(Unit) { detectTapGestures { at(it, this.size.width.toFloat()) } }
.pointerInput(Unit) { detectDragGestures { change, _ -> at(change.position, this.size.width.toFloat()); change.consume() } },
) {
val radius = this.size.minDimension / 2f
drawCircle(Brush.sweepGradient(List(7) { Color.hsv(it * 60f, 1f, 1f) }), radius)
drawCircle(Brush.radialGradient(listOf(Color.White, Color.Transparent), radius = radius), radius)
val theta = Math.toRadians(hue.toDouble())
val marker = Offset(radius + (kotlin.math.cos(theta) * sat * radius).toFloat(), radius + (kotlin.math.sin(theta) * sat * radius).toFloat())
drawCircle(Color.Black.copy(alpha = 0.55f), 9.dp.toPx(), marker)
drawCircle(rim, 7.dp.toPx(), marker)
drawCircle(Color.hsv(hue, sat, value), 5.dp.toPx(), marker)
}
}
@@ -1323,7 +1323,7 @@ internal fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = fa
modifier = Modifier.size(44.dp).clip(RoundedCornerShape(12.dp))
.background(if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
.glideBorder(hot, RoundedCornerShape(12.dp), pal.signal, pal.line2)
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick),
) {
if (busy) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
@@ -1342,7 +1342,7 @@ private fun SmallButton(text: String, enabled: Boolean = true, accent: Boolean =
modifier = modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(10.dp))
.background(if (hot) pal.signal else colors.surfaceVariant)
.glideBorder(hot, RoundedCornerShape(10.dp), colors.onBackground, pal.line2, restWidth = 2.dp)
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 14.dp, vertical = 8.dp),
) {
@@ -1422,7 +1422,7 @@ private fun ChoiceLine(
modifier = Modifier.padding(end = 6.dp).size(44.dp).clip(ROW_SHAPE)
.background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(delHot, ROW_SHAPE, colors.error)
.hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete)
.hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, onClick = onDelete)
.controllerConfirm(onClick = onDelete),
) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) }
}
@@ -23,7 +23,9 @@ import android.widget.TextView
import com.droiddeck.launcher.input.DeckControls
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadState
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import kotlin.math.atan2
import kotlin.math.hypot
import kotlin.math.min
@@ -85,9 +87,11 @@ class DeckControlsPanel(
addView(tabs, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, dp(44)))
}
addView(centre, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f))
addView(roundButton("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu, wide = true))
addView(space(dp(8)))
addView(roundButton("•••", context.getString(R.string.drawer_open_qam), onQam, wide = true))
if (SessionState.mode == SessionService.MODE_STEAM) {
addView(roundButton("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu, wide = true))
addView(space(dp(8)))
addView(roundButton("•••", context.getString(R.string.drawer_open_qam), onQam, wide = true))
}
}
private fun select(tab: Tab) {
@@ -177,8 +181,10 @@ class DeckControlsPanel(
place(pill("RB") { st, d -> st.press(PadState.RB, d) }, GamepadGeometry.Slot.RIGHT_INNER_SHOULDER)
place(pill("RT") { st, d -> st.rightTrigger = if (d) 1f else 0f }, GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER)
place(pill("VIEW") { st, d -> st.press(PadState.SELECT, d) }, GamepadGeometry.Slot.VIEW)
place(centreTap("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu), GamepadGeometry.Slot.STEAM)
place(centreTap("\u2022\u2022\u2022", context.getString(R.string.drawer_open_qam), onQam), GamepadGeometry.Slot.QAM)
if (SessionState.mode == SessionService.MODE_STEAM) {
place(centreTap("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu), GamepadGeometry.Slot.STEAM)
place(centreTap("\u2022\u2022\u2022", context.getString(R.string.drawer_open_qam), onQam), GamepadGeometry.Slot.QAM)
}
place(pill("MENU") { st, d -> st.press(PadState.START, d) }, GamepadGeometry.Slot.MENU)
place(centreTap("\u25a6 " + context.getString(R.string.deck_panels), context.getString(R.string.deck_more_controls)) { select(Tab.BOTH) },
GamepadGeometry.Slot.PANELS)
@@ -15,6 +15,7 @@ import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -105,7 +106,7 @@ fun DriverPage(
.glideBorder(refreshHot, RoundedCornerShape(10.dp), pal.signal, pal.line)
.focusRequester(refreshFocus)
.hoverable(refreshSrc)
.clickable(interactionSource = refreshSrc, indication = null, enabled = !checking, onClick = onRefresh),
.clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = refreshSrc, indication = null, enabled = !checking, onClick = onRefresh),
) {
if (checking) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
else Icon(Icons.Outlined.Refresh, contentDescription = stringResource(R.string.comp_check_drivers), tint = colors.onBackground, modifier = Modifier.size(20.dp))
@@ -185,7 +186,7 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f).then(modifier).focusRequester(mainFocus)
.then(if (row.removable) Modifier.focusProperties { right = delFocus } else Modifier)
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = onSelect)
.hoverable(src).selectable(selected = selected, role = androidx.compose.ui.semantics.Role.RadioButton, interactionSource = src, indication = null, onClick = onSelect)
.padding(horizontal = 11.dp, vertical = 8.dp),
) {
Box(
@@ -218,7 +219,7 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit
.glideBorder(delHot, RoundedCornerShape(10.dp), colors.error)
.focusRequester(delFocus)
.focusProperties { left = mainFocus }
.hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete),
.hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, onClick = onDelete),
) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, row.name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) }
}
}
@@ -235,7 +236,7 @@ internal fun FocusText(text: String, color: Color, modifier: Modifier = Modifier
modifier = modifier.clip(shape)
.background(if (hot) color.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(hot, shape, color)
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, onClick = onClick)
.padding(horizontal = 12.dp, vertical = 8.dp),
)
}
@@ -131,7 +131,7 @@ private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableIntera
.background(colors.surface)
.glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp)
.alpha(if (t.dim && !hot) 0.55f else 1f)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = t.onClick),
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = t.onClick),
) {
Box(modifier = Modifier.fillMaxWidth().shine(hot)) {
Art(t.art, t.iconRes, t.title, Modifier.fillMaxWidth(), wide, t.iconBitmap)
@@ -559,7 +559,7 @@ private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Uni
.clip(Shape12)
.background(if (selected) pal.signal.copy(alpha = 0.14f) else if (hovered) Color.White.copy(alpha = 0.05f) else Color.Transparent)
.glideBorder(focused, Shape12, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onSelect)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onSelect)
.controllerConfirm(onClick = onLaunch)
.padding(horizontal = 10.dp, vertical = 6.dp),
) {
@@ -22,6 +22,8 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
@@ -119,7 +121,7 @@ internal fun SideRail(
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier.fillMaxWidth(),
modifier = Modifier.fillMaxWidth().selectableGroup(),
) {
val place: (String) -> Modifier = { key ->
Modifier.onGloballyPositioned {
@@ -192,7 +194,7 @@ private fun RailItem(
.background(fill)
.glideBorder(focused, Shape14, pal.signal)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
.selectable(selected = current, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
.then(if (iconOnly) Modifier.semantics { contentDescription = label } else Modifier),
) {
if (iconOnly) Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(22.dp))
@@ -359,6 +359,7 @@ internal fun SetupPanel(
}
}
}
if (s.theme == Themes.GRADIENT) GradientColorRows()
ChoiceRow(
host, "app-scale", stringResource(R.string.setup_app_scale), stringResource(R.string.setup_app_scale_hint),
com.droiddeck.launcher.core.AppUiPrefs.scales.map { percent ->
@@ -790,3 +791,21 @@ private fun LanguageRow(host: MenuHost, chosen: String, onPick: (String) -> Unit
}
}
}
/** The two colours of the Gradient theme, each a small square that opens the colour picker. */
@Composable
private fun GradientColorRows() {
val ctx = androidx.compose.ui.platform.LocalContext.current.applicationContext
val (primary, secondary) = Themes.gradientColors
var picking by remember { androidx.compose.runtime.mutableIntStateOf(0) }
val primaryLabel = stringResource(R.string.theme_gradient_primary)
val secondaryLabel = stringResource(R.string.theme_gradient_secondary)
SettingsRow(primaryLabel, null) { ColorCube(androidx.compose.ui.graphics.Color(primary), primaryLabel) { picking = 1 } }
SettingsRow(secondaryLabel, null) { ColorCube(androidx.compose.ui.graphics.Color(secondary), secondaryLabel) { picking = 2 } }
if (picking != 0) ColorPickerDialog(
if (picking == 1) primaryLabel else secondaryLabel, if (picking == 1) primary else secondary,
onDismiss = { picking = 0 },
) { argb ->
if (picking == 1) Themes.setGradient(ctx, argb, secondary) else Themes.setGradient(ctx, primary, argb)
}
}
@@ -187,7 +187,7 @@ internal fun PrimaryButton(
.background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant)))
.then(if (enabled) Modifier else Modifier.border(1.dp, pal.line2, Shape12))
.then(if (hot) Modifier.border(2.dp, pal.signal, Shape12) else Modifier)
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled) {
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = null, enabled = enabled) {
placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) }
onClick()
}
@@ -250,7 +250,7 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boo
contentAlignment = Alignment.Center,
modifier = modifier.paneItem("btn:$text").downToFirstTile().heightIn(min = if (compact) 44.dp else 48.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).glideBorder(hot, Shape12, pal.signal, pal.line2)
.alpha(if (enabled) 1f else 0.5f)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = if (compact) 10.dp else 16.dp, vertical = if (compact) 7.dp else 11.dp),
) {
@@ -272,7 +272,7 @@ internal fun Cog(size: androidx.compose.ui.unit.Dp = 48.dp, onClick: () -> Unit)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.paneItem("cog").downToFirstTile().size(size).onGloballyPositioned { placed[0] = it }.clip(if (size > 48.dp) Shape14 else Shape12).background(Color.White.copy(alpha = 0.03f)).glideBorder(hot, if (size > 48.dp) Shape14 else Shape12, pal.signal, pal.line2)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current) {
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current) {
placed[0]?.takeIf { it.isAttached }?.let { PageOrigin.mark(Origin(it.boundsInRoot(), cornerPx)) }
spins++
onClick()
@@ -149,7 +149,8 @@ internal fun GlassesGroups(
}
}
if (display) SettingsGroup(g.model) {
if (g.experimental) SettingsRow(stringResource(R.string.glasses_control), stringResource(R.string.glasses_xreal_experimental)) {}
if (g.experimental) SettingsRow(stringResource(R.string.glasses_control), stringResource(
if (g.supportsDisplayModeControl) R.string.glasses_xreal_experimental else R.string.glasses_pro2_experimental)) {}
val status = if (g.hasDisplay) stringResource(R.string.glasses_status, g.width, g.height, kotlin.math.round(g.hz).toInt(),
stringResource(if (g.sbs) R.string.glasses_mode_3d else R.string.glasses_mode_2d)) else null
when {
@@ -168,7 +169,7 @@ internal fun GlassesGroups(
ToggleRow(host, "glasses-game", stringResource(R.string.glasses_game_on), stringResource(R.string.glasses_game_on_hint),
s.gameOnGlasses, chipModifier = track("glasses-game")) { Glasses.setGameOnGlasses(it) }
}
if (display && g.canControl && (inSession || g.sbs || g.sbsSupport == GlassesState.SBS_FAILS)) {
if (display && g.canControl && g.supportsDisplayModeControl && (inSession || g.sbs || g.sbsSupport == GlassesState.SBS_FAILS)) {
SettingsGroup(stringResource(R.string.glasses_display_mode)) {
if (g.sbsSupport == GlassesState.SBS_FAILS && !g.sbs) {
ActionRow(stringResource(R.string.glasses_3d), stringResource(R.string.glasses_3d_failed),
@@ -177,7 +178,7 @@ internal fun GlassesGroups(
g.sbs, chipModifier = track("glasses-3d")) { Glasses.set3d(it) }
}
}
if (display && g.canControl) {
if (display && g.canControl && g.supportsDisplayModeControl) {
val profiles = if (inSession) listOf(GlassesDisplayModes.profile(g.sbs, false))
else listOf(GlassesDisplayProfile.TWO_D, GlassesDisplayProfile.THREE_D)
for (profile in profiles) SettingsGroup(stringResource(if (profile == GlassesDisplayProfile.TWO_D)
@@ -214,9 +215,9 @@ internal fun GlassesGroups(
}
if (vr && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.cardboard_steamvr)) {
steamVr()
ToggleRow(host, "glasses-auto3d", stringResource(R.string.glasses_auto3d), stringResource(R.string.glasses_auto3d_hint),
s.auto3d, chipModifier = track("glasses-auto3d")) { Glasses.setAuto3d(it) }
if (g.canControl) {
if (g.supportsDisplayModeControl) ToggleRow(host, "glasses-auto3d", stringResource(R.string.glasses_auto3d),
stringResource(R.string.glasses_auto3d_hint), s.auto3d, chipModifier = track("glasses-auto3d")) { Glasses.setAuto3d(it) }
if (g.canControl && g.supportsDisplayModeControl) {
GlassesResolutionRow(host, g, s, GlassesDisplayProfile.VR, track)
if (steamVrRunning && tab != null) GlassesRefreshRow(host, g, s, track)
}
@@ -18,6 +18,8 @@ import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.detectVerticalDragGestures
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
@@ -715,7 +717,7 @@ internal fun SheetChips(
horizontalArrangement = Arrangement.spacedBy(ChipGap),
modifier = (if (equal) Modifier.fillMaxWidth() else Modifier)
.focusProperties { enter = { chips.getOrNull(selected) ?: FocusRequester.Default } }
.focusGroup(),
.focusGroup().selectableGroup(),
) {
labels.forEachIndexed { i, label ->
val m = (if (equal) Modifier.weight(1f) else Modifier.widthIn(min = least))
@@ -743,7 +745,7 @@ private fun SheetChip(label: String, on: Boolean, modifier: Modifier, onClick: (
.background(if (under) Color.Transparent else colors.surfaceVariant.copy(alpha = 0.5f))
.shownBar(on, pal.signal)
.glideBorder(hot, shape, pal.signal, if (under) Color.Transparent else pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
.hoverable(src).selectable(selected = on, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 14.dp, vertical = 8.dp),
) {
@@ -88,6 +88,7 @@ class ModeSettings(
val mangoapp: Boolean = true,
val steamController: String? = null,
val unfoldedControls: Boolean? = null,
val unfoldedControlsWithController: Boolean = false,
val runSteamAtStartup: Boolean = false,
val bootMovie: String? = null,
val bootMovieSound: Boolean = true,
@@ -140,6 +141,7 @@ class ModeSettingsActions(
val onReturnAfterGame: (Boolean) -> Unit = {},
val onSteamController: (String) -> Unit = {},
val onUnfoldedControls: (Boolean) -> Unit = {},
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
val onRunSteamAtStartup: (Boolean) -> Unit = {},
val onBootMovie: (String) -> Unit = {},
val onBootMovieSound: (Boolean) -> Unit = {},
@@ -290,6 +292,11 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
stringResource(R.string.unfolded_controls_hint),
s.unfoldedControls, onChange = a.onUnfoldedControls,
)
if (steam && s.unfoldedControls == true) ToggleRow(
host, "unfolded-controls-with-controller", stringResource(R.string.unfolded_controls_with_controller),
stringResource(R.string.unfolded_controls_with_controller_hint),
s.unfoldedControlsWithController, onChange = a.onUnfoldedControlsWithController,
)
if (steam) ChoiceRow(
host, "back-actions", stringResource(R.string.mode_back), stringResource(SessionPrefs.backActionsOrder(s.backActionsInverted)),
listOf(
@@ -234,7 +234,7 @@ private fun HeaderButton(text: String, onClick: () -> Unit) {
modifier = Modifier.fillMaxHeight()
.background(Color.White.copy(alpha = 0.08f), RoundedCornerShape(7.dp))
.glideBorder(focused, RoundedCornerShape(7.dp), pal.signal, Color.White.copy(alpha = 0.14f))
.clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.padding(horizontal = 12.dp),
) { Text(text, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = Color.White) }
}
@@ -157,16 +157,18 @@ class SecondScreenPresentation(
}
}
controls.addView(keyboardButton)
controls.addView(Button(context).apply {
text = "STEAM"
contentDescription = context.getString(R.string.deck_open_steam_menu)
setOnClickListener { onSteamMenu() }
})
controls.addView(Button(context).apply {
text = "…"
contentDescription = context.getString(R.string.drawer_open_qam)
setOnClickListener { onQam() }
})
if (SessionState.mode == SessionService.MODE_STEAM) {
controls.addView(Button(context).apply {
text = "STEAM"
contentDescription = context.getString(R.string.deck_open_steam_menu)
setOnClickListener { onSteamMenu() }
})
controls.addView(Button(context).apply {
text = "…"
contentDescription = context.getString(R.string.drawer_open_qam)
setOnClickListener { onQam() }
})
}
panel.addView(controls, FrameLayout.LayoutParams(-1, -2, Gravity.TOP))
root.addView(panel, weightParams())
val host = KeyboardHost(context) { sessionActivity.dispatchKeyEvent(it) }
@@ -278,6 +278,8 @@ class DrawerActions(
val onPipAutoEnter: (Boolean) -> Unit = {},
val unfoldedControls: Boolean? = null,
val onUnfoldedControls: (Boolean) -> Unit = {},
val unfoldedControlsWithController: Boolean = false,
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
val onShareLogs: () -> Unit,
val onStop: () -> Unit,
val onStopFrom: ((androidx.compose.ui.geometry.Rect?) -> Unit)? = null,
@@ -313,7 +315,7 @@ class DrawerActions(
@OptIn(ExperimentalComposeUiApi::class)
@Composable
internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, controllerActive: Boolean, onPageChange: (SessionDrawerPage) -> Unit, a: DrawerActions) {
val pages = sessionDrawerPages(a.steam && a.secondScreenDisplays.isNotEmpty(), a.glassesPresent)
val pages = sessionDrawerPages(a.secondScreenDisplays.isNotEmpty(), a.glassesPresent)
val page = requestedPage.takeIf { it in pages } ?: SessionDrawerPage.CONTROLLER
LaunchedEffect(requestedPage, pages) { if (page != requestedPage) onPageChange(page) }
val colors = MaterialTheme.colorScheme
@@ -575,6 +577,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls),
stringResource(R.string.unfolded_controls_hint), a.unfoldedControls,
chipModifier = focus.track(page, "unfolded-controls"), onChange = a.onUnfoldedControls)
if (a.steam && a.unfoldedControls == true) ToggleRow(host, "unfolded-controls-with-controller",
stringResource(R.string.unfolded_controls_with_controller),
stringResource(R.string.unfolded_controls_with_controller_hint), a.unfoldedControlsWithController,
chipModifier = focus.track(page, "unfolded-controls-with-controller"),
onChange = a.onUnfoldedControlsWithController)
}
SettingsGroup(stringResource(R.string.drawer_latency)) {
ToggleRow(host, "low-latency-controller", stringResource(R.string.drawer_low_latency_controller),
@@ -754,7 +761,7 @@ private fun DrawerActionButton(text: String, icon: androidx.compose.ui.graphics.
modifier = modifier.fillMaxWidth().heightIn(min = 52.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.16f) else colors.surfaceVariant)
.glideBorder(hot, shape, pal.signal)
.hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, onClick = onClick)
.hoverable(source).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = source, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick).padding(horizontal = 16.dp, vertical = 10.dp),
) {
Icon(icon, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(22.dp))
@@ -791,7 +798,7 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = modifier.heightIn(min = 44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop")
.clip(shape).background(fill).glideBorder(hot, shape, colors.error.copy(alpha = 0.9f), colors.error.copy(alpha = 0.55f))
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(start = 12.dp, end = 14.dp),
) {
@@ -817,7 +824,7 @@ private fun SteamActionPill(
.clip(shape).background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(interactionSource)
.clickable(interactionSource = interactionSource, indication = LocalIndication.current, onClick = onClick)
.clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = interactionSource, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onConfirm ?: onClick),
) {
Icon(icon, contentDescription = null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(20.dp))
@@ -836,7 +843,7 @@ private fun DrawerBumper(label: String, description: String, modifier: Modifier
contentAlignment = Alignment.Center,
modifier = modifier.size(44.dp).clip(ring)
.glideBorder(hot, ring, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, onClick = onClick)
.controllerConfirm(onClick = onClick)
.semantics { contentDescription = description },
) {
@@ -857,7 +864,7 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag
val motion = Motion.tw<Float>(340, easing = FastOutSlowInEasing)
androidx.compose.foundation.layout.BoxWithConstraints(
contentAlignment = Alignment.Center,
modifier = modifier.height(if (compact) 44.dp else 64.dp).clipToBounds(),
modifier = modifier.height(if (compact) 44.dp else 64.dp).clipToBounds().selectableGroup(),
) {
val tab = if (compact) 36f else 44f
val spacing = ((maxWidth.value - tab) / ((count - 1) * (1f + DRAWER_TAB_LEAN_DP / DRAWER_TAB_SPACING_DP))).coerceIn(24f, DRAWER_TAB_SPACING_DP)
@@ -890,7 +897,7 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag
.semantics { contentDescription = pageDescription }
.testTag("drawer-tab-${item.name.lowercase()}")
.hoverable(source)
.clickable(interactionSource = source, indication = LocalIndication.current, onClick = select)
.selectable(selected = selected, role = androidx.compose.ui.semantics.Role.Tab, interactionSource = source, indication = LocalIndication.current, onClick = select)
.controllerConfirm(onClick = select),
) {
Icon(item.icon, contentDescription = null, tint = tint, modifier = Modifier.size(if (compact) 22.dp else 30.dp))
@@ -1704,7 +1711,7 @@ private fun ConfirmChoice(label: String, danger: Boolean, enabled: Boolean, modi
.background(if (hot) accent.copy(alpha = if (danger) 0.18f else 0.14f) else Color.Transparent)
.glideBorder(hot, shape, accent)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 16.dp),
) {
@@ -36,6 +36,8 @@ import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
@@ -177,7 +179,7 @@ internal fun TabStrip(
if (bumpers) BumperKey("LB", stringResource(R.string.widgets_prev_tab)) { onSelect((selected + tabs.size - 1) % tabs.size) }
Row(
modifier = Modifier.weight(1f, fill = false).clip(shape).background(colors.surfaceVariant).border(1.dp, pal.line2, shape)
.horizontalScroll(scroll).padding(3.dp),
.horizontalScroll(scroll).selectableGroup().padding(3.dp),
) {
tabs.forEachIndexed { i, label ->
val on = i == selected
@@ -197,7 +199,7 @@ internal fun TabStrip(
.clip(tabShape)
.background(if (on) pal.signal else if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
.glideBorder(hot, tabShape, if (on) colors.onBackground else pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Tab, onClick = pick)
.hoverable(src).selectable(selected = on, interactionSource = src, indication = null, role = Role.Tab, onClick = pick)
.controllerConfirm(onClick = pick)
.padding(horizontal = tabPadding, vertical = if (compact) 6.dp else 12.dp),
)
@@ -367,7 +369,7 @@ fun MenuItem(
.clip(RoundedCornerShape(8.dp))
.background(if (hot && enabled) Color.White.copy(alpha = 0.07f) else Color.Transparent)
.alpha(if (enabled) 1f else 0.4f)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 10.dp, vertical = 9.dp),
) {
@@ -400,7 +402,7 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
.background(colors.surfaceVariant)
.glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, if (open) pal.signal else pal.line2)
.alpha(if (enabled) 1f else 0.5f)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 12.dp, vertical = 8.dp),
) {
@@ -791,7 +793,7 @@ fun <T> SegmentedTabs(options: List<Pair<T, String>>, selected: T?, modifier: Mo
.graphicsLayer { alpha = shown }
.clip(pillShape).background(pal.signal),
)
Row {
Row(Modifier.selectableGroup()) {
options.forEachIndexed { i, (value, label) ->
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
@@ -810,9 +812,8 @@ fun <T> SegmentedTabs(options: List<Pair<T, String>>, selected: T?, modifier: Mo
modifier = tabModifier(value).width(segment).fillMaxHeight()
.clip(pillShape)
.glideBorder(hot, pillShape, if (chosen) pal.onSignal else pal.signal)
.semantics { role = Role.Tab; this.selected = chosen }
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, onClick = pick)
.selectable(selected = chosen, role = Role.Tab, interactionSource = src, indication = LocalIndication.current, onClick = pick)
.controllerConfirm(onClick = pick),
) {
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = ink, maxLines = 1, softWrap = false)
@@ -370,7 +370,7 @@ internal fun DrawerAchievementsRow(progress: Pair<Int, Int>?, modifier: Modifier
modifier = modifier.fillMaxWidth().height(44.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface)
.glideBorder(hot, shape, pal.signal, pal.line)
.clickable(interactionSource = interaction, indication = LocalIndication.current, onClick = onClick)
.clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = interaction, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 12.dp),
) {
@@ -60,6 +60,8 @@ import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
@@ -1150,7 +1152,7 @@ private fun HeaderTabs(labels: List<String>, selected: Int, onSelect: (Int) -> U
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = RoundedCornerShape(8.dp)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.selectableGroup()) {
labels.forEachIndexed { i, label ->
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
@@ -1159,7 +1161,7 @@ private fun HeaderTabs(labels: List<String>, selected: Int, onSelect: (Int) -> U
label, fontSize = 15.sp, fontWeight = FontWeight.Bold, maxLines = 1,
color = if (i == selected || hot) colors.onBackground else colors.onSurfaceVariant.copy(alpha = 0.7f),
modifier = Modifier.clip(shape).glideBorder(hot, shape, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = pick)
.hoverable(src).selectable(selected = i == selected, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = pick)
.controllerConfirm(onClick = pick)
.padding(horizontal = 4.dp, vertical = 6.dp),
)
@@ -1363,7 +1365,7 @@ private fun GameListRow(
modifier = Modifier.fillMaxWidth().heightIn(min = 64.dp).then(navigation).paneItem("card:${item.key}")
.then(if (first) Modifier.firstTile() else Modifier)
.clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open)
.padding(horizontal = 10.dp, vertical = 8.dp),
) {
CardArt(item, Modifier.width(96.dp).height(54.dp).clip(RoundedCornerShape(8.dp)))
@@ -1481,7 +1483,7 @@ private fun GameCard(
}
.then(navigation).paneItem("card:${item.key}").then(if (first) Modifier.firstTile() else Modifier).graphicsLayer { scaleX = scale; scaleY = scale }
.clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open),
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open),
) {
CardFace(item, download, hot, capsule) { CardMarker(item, installed, download, compact = capsule) }
}
@@ -6,6 +6,10 @@ import androidx.compose.material3.darkColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import android.content.Context
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
@@ -29,6 +33,30 @@ object Themes {
const val PAPER = "paper"
const val ICON_BLUE = "blue"
const val ELECTRIC = "electric"
const val GRADIENT = "gradient"
const val DEFAULT_PRIMARY = 0xFF8B5CF6.toInt()
const val DEFAULT_SECONDARY = 0xFF22D3EE.toInt()
/** The two colours of the custom Gradient theme: primary, then secondary. Changing them restyles the app at once. */
var gradientColors by mutableStateOf(DEFAULT_PRIMARY to DEFAULT_SECONDARY)
private set
fun loadGradient(context: Context) {
gradientColors = SessionPrefs.gradientColors(context)
}
fun setGradient(context: Context, primary: Int, secondary: Int) {
SessionPrefs.setGradientColors(context, primary, secondary)
gradientColors = primary to secondary
}
/** The theme the person chose, with the custom colours read first; for code that is not in a composition. */
fun current(context: Context): Palette {
val id = SessionPrefs.theme(context)
if (id == GRADIENT) loadGradient(context)
return byId(id)
}
val all: List<Palette> = listOf(
Palette(
@@ -59,9 +87,13 @@ object Themes {
primary = Color(0xFF2E86FF), primary2 = Color(0xFF2684FF), onPrimary = Color(0xFF03111F), signal = Color(0xFF2E86FF),
good = Color(0xFF4CD37F),
),
ThemeColors.palette(DEFAULT_PRIMARY, DEFAULT_SECONDARY, R.string.theme_gradient, R.string.theme_gradient_detail),
)
fun byId(id: String): Palette = all.firstOrNull { it.id == id } ?: all[0]
fun byId(id: String): Palette {
if (id == GRADIENT) return ThemeColors.palette(gradientColors.first, gradientColors.second, R.string.theme_gradient, R.string.theme_gradient_detail)
return all.firstOrNull { it.id == id } ?: all[0]
}
}
val LocalPalette = staticCompositionLocalOf { Themes.byId(Themes.GRAPHITE) }
@@ -0,0 +1,157 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.toArgb
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
/** Colour maths for the custom gradient theme: hue, saturation and brightness in, a readable palette out. */
internal object ThemeColors {
/** Hue 0..360, saturation and brightness 0..1. */
class Hsv(val h: Float, val s: Float, val v: Float)
fun toHsv(argb: Int): Hsv {
val r = (argb shr 16 and 0xFF) / 255f
val g = (argb shr 8 and 0xFF) / 255f
val b = (argb and 0xFF) / 255f
val top = max(r, max(g, b))
val delta = top - min(r, min(g, b))
val hue = when {
delta == 0f -> 0f
top == r -> 60f * (((g - b) / delta) % 6f)
top == g -> 60f * ((b - r) / delta + 2f)
else -> 60f * ((r - g) / delta + 4f)
}
return Hsv(if (hue < 0f) hue + 360f else hue, if (top == 0f) 0f else delta / top, top)
}
fun fromHsv(h: Float, s: Float, v: Float): Int =
Color.hsv(h.mod(360f), s.coerceIn(0f, 1f), v.coerceIn(0f, 1f)).toArgb()
fun hex(argb: Int): String = "#%06X".format(argb and 0xFFFFFF)
/** `#RRGGBB`, `RRGGBB` or `#RGB`; null for anything else. */
fun parseHex(text: String): Int? {
val digits = text.trim().removePrefix("#")
if (!digits.all { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }) return null
val full = when (digits.length) {
3 -> digits.map { "$it$it" }.joinToString("")
6 -> digits
else -> return null
}
return 0xFF000000.toInt() or full.toInt(16)
}
private const val MIN_LUMINANCE = 0.10f
/** The colour, made brighter (then paler, for a deep blue that brightness alone cannot lift) when it is too dark to show on the dark background. */
fun readable(argb: Int): Int {
if (Color(argb).luminance() >= MIN_LUMINANCE) return argb or 0xFF000000.toInt()
val hsv = toHsv(argb)
var v = hsv.v
var s = hsv.s
var out = argb
while (v < 1f && Color(out).luminance() < MIN_LUMINANCE) {
v = min(1f, v + 0.04f)
out = fromHsv(hsv.h, s, v)
}
while (s > 0f && Color(out).luminance() < MIN_LUMINANCE) {
s = max(0f, s - 0.04f)
out = fromHsv(hsv.h, s, v)
}
return out
}
/** A dark neutral tinted with the primary's hue; plain greys stay grey. */
fun tint(primary: Int, saturation: Float, brightness: Float): Color {
val hsv = toHsv(primary)
val strength = (hsv.s / 0.35f).coerceIn(0f, 1f)
return Color(fromHsv(hsv.h, saturation * strength, brightness))
}
private val DARK_INK = Color(0xFF03111F)
private fun contrast(a: Color, b: Color): Float {
val x = a.luminance()
val y = b.luminance()
return (max(x, y) + 0.05f) / (min(x, y) + 0.05f)
}
/** Dark or white text, whichever reads better on the worse of the two gradient colours. */
internal fun inkFor(first: Int, second: Int): Color {
fun worst(ink: Color) = min(contrast(ink, Color(first)), contrast(ink, Color(second)))
return if (worst(DARK_INK) >= worst(Color.White)) DARK_INK else Color.White
}
private const val MIN_CONTRAST = 4.5f
/** The colour nudged just enough, lighter for dark text and darker for white text, to give [ink] a readable contrast on it. */
private fun fitTo(ink: Color, argb: Int): Int {
fun short(color: Int) = contrast(ink, Color(color)) < MIN_CONTRAST
if (!short(argb)) return argb
val hsv = toHsv(argb)
var v = hsv.v
var s = hsv.s
var out = argb
if (ink == DARK_INK) {
while (v < 1f && short(out)) { v = min(1f, v + 0.04f); out = fromHsv(hsv.h, s, v) }
while (s > 0f && short(out)) { s = max(0f, s - 0.04f); out = fromHsv(hsv.h, s, v) }
} else {
while (v > 0f && short(out)) { v = max(0f, v - 0.04f); out = fromHsv(hsv.h, s, v) }
}
return out
}
private fun gradientColor(first: Int, second: Int, fraction: Float): Int {
fun channel(shift: Int): Int {
val a = first shr shift and 0xFF
val b = second shr shift and 0xFF
return (a + (b - a) * fraction).roundToInt().coerceIn(0, 255)
}
return (0xFF shl 24) or (channel(16) shl 16) or (channel(8) shl 8) or channel(0)
}
private fun gradientFits(ink: Color, first: Int, second: Int): Boolean =
(0..32).all { step ->
val color = gradientColor(first, second, step / 32f)
contrast(ink, Color(color)) >= MIN_CONTRAST + 0.02f
}
private fun moveTowardContrast(ink: Color, argb: Int): Int {
val hsv = toHsv(argb)
return if (ink == DARK_INK) {
when {
hsv.v < 1f -> fromHsv(hsv.h, hsv.s, min(1f, hsv.v + 0.04f))
hsv.s > 0f -> fromHsv(hsv.h, max(0f, hsv.s - 0.04f), hsv.v)
else -> argb
}
} else {
fromHsv(hsv.h, hsv.s, max(0f, hsv.v - 0.04f))
}
}
fun palette(primary: Int, secondary: Int, label: Int, detail: Int): Palette {
val seen = readable(primary)
val seenSecond = readable(secondary)
val ink = inkFor(seen, seenSecond)
var first = fitTo(ink, seen)
var second = fitTo(ink, seenSecond)
while (!gradientFits(ink, first, second)) {
val nextFirst = moveTowardContrast(ink, first)
val nextSecond = moveTowardContrast(ink, second)
if (nextFirst == first && nextSecond == second) break
first = nextFirst
second = nextSecond
}
return Palette(
Themes.GRADIENT, label, detail,
background = tint(first, 0.50f, 0.045f), surface = tint(first, 0.45f, 0.075f), surfaceVariant = tint(first, 0.42f, 0.115f),
line = tint(first, 0.40f, 0.16f), line2 = tint(first, 0.36f, 0.22f),
onBackground = tint(first, 0.05f, 0.97f), onSurfaceVariant = tint(first, 0.16f, 0.68f),
primary = Color(first), primary2 = Color(second), onPrimary = ink, signal = Color(first),
good = Color(0xFF4CD37F),
)
}
}
@@ -16,7 +16,7 @@ import com.droiddeck.launcher.session.SessionPrefs
internal class TrackingRecoveryView(context: Context) : View(context) {
private var recovery: TrackingRecovery? = null
private var stereo = false
private var palette = Themes.byId(SessionPrefs.theme(context))
private var palette = Themes.current(context)
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var blocks = emptyList<StaticLayout>()
@@ -26,7 +26,7 @@ internal class TrackingRecoveryView(context: Context) : View(context) {
importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_YES
}
fun update(state: TrackingRecovery?, stereo: Boolean, palette: Palette = Themes.byId(SessionPrefs.theme(context))) {
fun update(state: TrackingRecovery?, stereo: Boolean, palette: Palette = Themes.current(context)) {
if (recovery == state && this.stereo == stereo && this.palette == palette) return
recovery = state
this.stereo = stereo