mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 20:36:04 +00:00
Merge remote-tracking branch 'origin/main' into fix/pr-1301-filemanager-safety
This commit is contained in:
commit
9c1cacd8f4
114 files changed
+5310
-287
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)
|
||||
|
||||
@@ -2012,7 +2012,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()
|
||||
}
|
||||
@@ -3418,7 +3418,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 +3449,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
|
||||
|
||||
@@ -54,7 +54,12 @@ public final class Downloader {
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
if (expectedSha256 != null && !expectedSha256.matches("(?i)[0-9a-f]{64}"))
|
||||
throw new IllegalArgumentException("Expected SHA-256 must be 64 hex characters");
|
||||
return downloadCandidates(url, DownloadSource.INSTANCE.candidates(url), destination, resume, expectedSha256, progress);
|
||||
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, progress);
|
||||
}
|
||||
|
||||
/** A third-party mirror may only serve bytes that can be checked against a digest from a direct source. */
|
||||
static List<String> sources(String url, String expectedSha256) {
|
||||
return expectedSha256 == null ? java.util.Collections.singletonList(url) : DownloadSource.INSTANCE.candidates(url);
|
||||
}
|
||||
|
||||
// Package-private for the local multi-source HTTP test.
|
||||
|
||||
@@ -2,14 +2,51 @@ package com.droiddeck.launcher.core
|
||||
|
||||
object LogRedactor {
|
||||
private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}")
|
||||
private val HIDL_SHARED_LIBRARY = Regex(
|
||||
"(?:android\\.(?:hardware|frameworks|hidl|system)|vendor\\.[A-Za-z0-9_]+\\.hardware)" +
|
||||
"(?:\\.[A-Za-z0-9_]+)+@[0-9]+\\.[0-9]+(?:-[A-Za-z0-9_]+)*\\.so"
|
||||
)
|
||||
private val hidlMatcher = object : ThreadLocal<java.util.regex.Matcher>() {
|
||||
override fun initialValue(): java.util.regex.Matcher = HIDL_SHARED_LIBRARY.toPattern().matcher("")
|
||||
}
|
||||
|
||||
private fun isHidlLoaderDiagnostic(input: String, match: MatchResult): Boolean {
|
||||
val matcher = hidlMatcher.get()!!
|
||||
val isLibrary = try { matcher.reset(match.value).matches() } finally { matcher.reset("") }
|
||||
if (!isLibrary) return false
|
||||
val start = match.range.first
|
||||
val end = match.range.last + 1
|
||||
val prefix = "library \""
|
||||
val suffix = "\" not found"
|
||||
val earliestQuote = (start - 4096).coerceAtLeast(0)
|
||||
var quote = start - 1
|
||||
while (quote >= earliestQuote && input[quote] != '"') {
|
||||
val char = input[quote]
|
||||
if (!char.isLetterOrDigit() && char !in "/._-") return false
|
||||
quote--
|
||||
}
|
||||
if (quote < earliestQuote) return false
|
||||
val pathStart = quote + 1
|
||||
if (pathStart < start && (input[start - 1] != '/' ||
|
||||
!(input.regionMatches(pathStart, "/vendor/", 0, 8) ||
|
||||
input.regionMatches(pathStart, "/system/", 0, 8)))) return false
|
||||
val prefixStart = quote - prefix.length + 1
|
||||
val suffixEnd = end + suffix.length
|
||||
return prefixStart >= 0 && suffixEnd <= input.length &&
|
||||
input.regionMatches(prefixStart, prefix, 0, prefix.length, ignoreCase = true) &&
|
||||
input.regionMatches(end, suffix, 0, suffix.length, ignoreCase = true) &&
|
||||
(prefixStart == 0 || !(input[prefixStart - 1].isLetterOrDigit() || input[prefixStart - 1] == '_')) &&
|
||||
(suffixEnd == input.length || !(input[suffixEnd].isLetterOrDigit() || input[suffixEnd] == '_'))
|
||||
}
|
||||
|
||||
private val JWT_LABELLED = Regex("(?i)(\\bJWT[\\s=:]+)(\\d{8,})")
|
||||
private val JWT_BASE64 = Regex("ey[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}")
|
||||
private val GUID = Regex("\\b[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\\b")
|
||||
private val SECRET_KV = Regex(
|
||||
"(?i)\\b(access[_-]?token|refresh[_-]?token|auth[_-]?token|authtoken|token|authcode|" +
|
||||
"(?i)(\\b(?:access[_-]?token|refresh[_-]?token|auth[_-]?token|authtoken|token|authcode|" +
|
||||
"auth[_-]?ticket|ticket|sessionid|steamloginsecure|webapikey|api[_-]?key|" +
|
||||
"machine[_-]?auth(?:[_-]?token)?|machineauth|password|passwd|pwd|secret)" +
|
||||
"(\\s*[=:]\\s*|=)([^\\s\"'<>&;,]{4,})"
|
||||
"machine[_-]?auth(?:[_-]?token)?|machineauth|password|passwd|pwd|secret)[\"']?\\s*[=:]\\s*)" +
|
||||
"(?:([\"'])((?:\\\\.|(?!\\2)[^\\\\\\r\\n]){4,})\\2|([^\\s\"'<>&;,]{4,}))"
|
||||
)
|
||||
private val GUARD_CODE = Regex(
|
||||
"(?i)((?:steam\\s*)?guard\\s*code[\\s:=]*|two[\\s-]?factor[\\s:=]*|2fa[\\s:=]*)([A-Za-z0-9]{5})"
|
||||
@@ -291,7 +328,7 @@ object LogRedactor {
|
||||
if (out.has("jwt")) out.set(JWT_LABELLED.replace(out.text) { "${it.groupValues[1]}<redacted:jwt>" })
|
||||
if ("ey" in out.text) out.set(JWT_BASE64.replace(out.text, "<redacted:jwt>"))
|
||||
if (out.has("token", "auth", "ticket", "sessionid", "steamloginsecure", "api", "machine", "pass", "pwd", "secret")) {
|
||||
out.set(SECRET_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}<redacted:token>" })
|
||||
out.set(SECRET_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}<redacted:token>${it.groupValues[2]}" })
|
||||
}
|
||||
if (out.has("guard", "factor", "2fa")) out.set(GUARD_CODE.replace(out.text) { "${it.groupValues[1]}<redacted:code>" })
|
||||
if (out.hasRun(32, ::isHex)) out.set(WEBAPI_KEY.replace(out.text, "<redacted:key>"))
|
||||
@@ -309,7 +346,9 @@ object LogRedactor {
|
||||
}
|
||||
if (out.has("login")) out.set(LOGIN_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" })
|
||||
for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "<redacted:account>"))
|
||||
if ('@' in out.text) out.set(EMAIL.replace(out.text, "<redacted:email>"))
|
||||
if ('@' in out.text) out.set(EMAIL.replace(out.text) { m ->
|
||||
m.value.takeIf { isHidlLoaderDiagnostic(out.text, m) } ?: "<redacted:email>"
|
||||
})
|
||||
if (out.has("jwt", "token", "ticket", "sessionid", "steamloginsecure", "machineauth")) {
|
||||
out.set(RESIDUAL.replace(out.text) { "${it.groupValues[1]}=<redacted:token>" })
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -117,6 +117,16 @@ public final class PadBridge {
|
||||
if (changed && !on) resetBuiltin();
|
||||
}
|
||||
|
||||
private static volatile int firstSlot;
|
||||
|
||||
public static void setFirstSlot(int slot) {
|
||||
firstSlot = slot;
|
||||
}
|
||||
|
||||
private int firstPlayerSlot() {
|
||||
return firstSlot;
|
||||
}
|
||||
|
||||
private void resetBuiltin() {
|
||||
routedTouch.clear();
|
||||
systemGuidePressed = false;
|
||||
@@ -252,7 +262,9 @@ public final class PadBridge {
|
||||
public synchronized void syncConnectedControllers() {
|
||||
for (int deviceId : InputDevice.getDeviceIds()) {
|
||||
InputDevice device = InputDevice.getDevice(deviceId);
|
||||
if (isFromController(device) && !excluded.test(deviceId)) publish(slotFor(device));
|
||||
if (!isFromController(device) || excluded.test(deviceId)) continue;
|
||||
int slot = slotFor(device);
|
||||
if (slot >= 0) publish(slot);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,6 +284,7 @@ public final class PadBridge {
|
||||
public synchronized boolean onKeyEvent(KeyEvent event) {
|
||||
if (!isControllerKeyEvent(event) || excluded.test(event.getDeviceId())) return false;
|
||||
int slot = slotFor(event.getDevice());
|
||||
if (slot < 0) return false;
|
||||
int side = JoyCon.side(event.getDevice());
|
||||
if (side >= 0 && partners[slot] != NO_CONTROLLER && JoyCon.isRail(side, event.getScanCode())) return true;
|
||||
PadState pad = stateFor(slot);
|
||||
@@ -320,6 +333,7 @@ public final class PadBridge {
|
||||
if (!isControllerMotionEvent(event) || excluded.test(event.getDeviceId())) return false;
|
||||
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
|
||||
int slot = slotFor(event.getDevice());
|
||||
if (slot < 0) return false;
|
||||
PadState pad = stateFor(slot);
|
||||
noteDevice(event.getDevice(), slot);
|
||||
statAxes++;
|
||||
@@ -534,25 +548,25 @@ public final class PadBridge {
|
||||
if (owners[slot] != NO_CONTROLLER && InputDevice.getDevice(owners[slot]) == null) leave(slot, owners[slot]);
|
||||
}
|
||||
int side = JoyCon.side(device);
|
||||
for (int slot = 0; side >= 0 && slot < SLOTS; slot++) {
|
||||
for (int slot = firstPlayerSlot(); side >= 0 && slot < SLOTS; slot++) {
|
||||
if (owners[slot] == NO_CONTROLLER || partners[slot] != NO_CONTROLLER) continue;
|
||||
InputDevice owner = InputDevice.getDevice(owners[slot]);
|
||||
if (JoyCon.side(owner) != 1 - side) continue;
|
||||
partners[slot] = id;
|
||||
slotJoyCons.set(slot * 2 + side, id);
|
||||
slotJoyCons.set(slot * 2 + 1 - side, owner.getId());
|
||||
if (slot == 0) releaseBackPaddles();
|
||||
if (slot == firstPlayerSlot()) releaseBackPaddles();
|
||||
stateFor(slot).clear();
|
||||
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") joins \"" + owner.getName() + "\" as player " + (slot + 1));
|
||||
return slot;
|
||||
}
|
||||
for (int slot = 0; slot < SLOTS; slot++) {
|
||||
for (int slot = firstPlayerSlot(); slot < SLOTS; slot++) {
|
||||
if (owners[slot] != NO_CONTROLLER) continue;
|
||||
owners[slot] = id;
|
||||
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") is player " + (slot + 1));
|
||||
return slot;
|
||||
}
|
||||
return 0;
|
||||
return -1;
|
||||
}
|
||||
|
||||
private PadState stateFor(int slot) {
|
||||
@@ -561,7 +575,8 @@ public final class PadBridge {
|
||||
|
||||
private boolean isPrimary(KeyEvent event) {
|
||||
int id = event.getDevice().getId();
|
||||
return owners[0] == id || partners[0] == id;
|
||||
int first = firstPlayerSlot();
|
||||
return owners[first] == id || partners[first] == id;
|
||||
}
|
||||
|
||||
private void releaseBackPaddles() {
|
||||
@@ -580,7 +595,7 @@ public final class PadBridge {
|
||||
clearJoyCons(slot);
|
||||
if (slotControllers.get(slot) == id) slotControllers.set(slot, owners[slot]);
|
||||
if (activeControllerId == id) activeControllerId = owners[slot];
|
||||
if (slot == 0) releaseBackPaddles();
|
||||
if (slot == firstPlayerSlot()) releaseBackPaddles();
|
||||
stateFor(slot).clear();
|
||||
publish(slot);
|
||||
}
|
||||
@@ -596,8 +611,8 @@ public final class PadBridge {
|
||||
partners[slot] = NO_CONTROLLER;
|
||||
clearJoyCons(slot);
|
||||
slotControllers.set(slot, NO_CONTROLLER);
|
||||
if (slot == firstPlayerSlot()) releaseBackPaddles();
|
||||
if (slot == 0) {
|
||||
releaseBackPaddles();
|
||||
state.clear();
|
||||
publish();
|
||||
return;
|
||||
|
||||
@@ -118,7 +118,8 @@ object DesktopCatalog {
|
||||
|
||||
fun desktopPresent(context: Context): Boolean {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
return File(root, DesktopRemoval.PENDING).exists() || marker(context, DESKTOP_ID).exists()
|
||||
return File(root, DesktopRemoval.PENDING).exists() || marker(context, DESKTOP_ID).exists() ||
|
||||
journal(root, DESKTOP_ID).exists()
|
||||
}
|
||||
|
||||
fun desktopSize(context: Context): Long = DesktopRemoval.installedSize(context)
|
||||
@@ -126,8 +127,21 @@ object DesktopCatalog {
|
||||
fun cleanLegacy(context: Context, listener: LinuxRuntimeInstaller.ProgressListener? = null) =
|
||||
DesktopRemoval.cleanLegacy(context, listener)
|
||||
|
||||
fun removeDesktop(context: Context, listener: LinuxRuntimeInstaller.ProgressListener): String? =
|
||||
fun removeDesktop(context: Context, listener: LinuxRuntimeInstaller.ProgressListener): String? = synchronized(installLock) {
|
||||
DesktopRemoval.remove(context, listener)
|
||||
}
|
||||
|
||||
internal fun discardDesktopInstall(context: Context) {
|
||||
val entry = interrupted(context).firstOrNull { it.id == DESKTOP_ID }
|
||||
val journal = journal(LinuxRuntime.rootDir(context), DESKTOP_ID)
|
||||
entry?.let {
|
||||
val download = downloadFile(context, it)
|
||||
for (file in listOf(download, File(download.path + ".resume.properties"))) {
|
||||
check(!file.exists() || file.delete()) { "Could not remove desktop download ${file.name}" }
|
||||
}
|
||||
}
|
||||
check(!journal.exists() || journal.delete()) { "Could not clear desktop installation" }
|
||||
}
|
||||
|
||||
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
|
||||
installLocked(context, entry, listener)
|
||||
|
||||
@@ -44,9 +44,10 @@ internal object DesktopRemoval {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val pending = File(root, PENDING)
|
||||
val marker = File(root, ".droiddeck-pkg-${DesktopCatalog.DESKTOP_ID}")
|
||||
val version = FileUtils.readString(pending)?.trim() ?: FileUtils.readString(marker)?.trim()
|
||||
val installing = DesktopCatalog.interrupted(root).firstOrNull { it.id == DesktopCatalog.DESKTOP_ID }
|
||||
val version = FileUtils.readString(pending)?.trim() ?: installing?.version ?: FileUtils.readString(marker)?.trim()
|
||||
val versions = context.assets.open("desktop-removal/versions.txt").bufferedReader().use { it.readLines() }
|
||||
check(version in versions) { context.getString(R.string.desktop_removal_unknown) }
|
||||
check(version in versions && (installing == null || installing.version in versions)) { context.getString(R.string.desktop_removal_unknown) }
|
||||
val entries = lines(context, "kde-remove.tsv.gzip").map(DesktopFileRemoval.Entry::parse)
|
||||
val keep = protected(context, root)
|
||||
cleanLegacy(context, listener)
|
||||
@@ -63,6 +64,7 @@ internal object DesktopRemoval {
|
||||
if (!target.delete()) error("Could not remove $path")
|
||||
}
|
||||
}
|
||||
DesktopCatalog.discardDesktopInstall(context)
|
||||
if (!pending.delete()) error("Could not finish desktop removal")
|
||||
Log.i("DesktopRemoval", "KDE: $result")
|
||||
listener.onProgress(context.getString(R.string.desktop_removed), 100)
|
||||
|
||||
@@ -13,6 +13,7 @@ import com.caverock.androidsvg.SVG
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.core.Hashes
|
||||
import com.droiddeck.launcher.store.FlathubApi
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
@@ -44,7 +45,7 @@ object UserApps {
|
||||
val fex: String = LinuxFex.AUTO, val arch: String? = null,
|
||||
)
|
||||
|
||||
class Release(val tag: String, val published: String, val asset: String, val url: String)
|
||||
class Release(val tag: String, val published: String, val asset: String, val url: String, val sha256: String? = null)
|
||||
|
||||
sealed class UpdateCheck {
|
||||
class Current(val tag: String) : UpdateCheck()
|
||||
@@ -318,9 +319,12 @@ object UserApps {
|
||||
val r = releases.getJSONObject(i)
|
||||
if (r.optBoolean("draft")) return@mapNotNull null
|
||||
val assets = r.optJSONArray("assets") ?: return@mapNotNull null
|
||||
val byName = (0 until assets.length()).associate { j -> assets.getJSONObject(j).let { it.getString("name") to it.getString("browser_download_url") } }
|
||||
val byName = (0 until assets.length()).associate { j -> assets.getJSONObject(j).let { it.getString("name") to it } }
|
||||
pickAsset(byName.keys.toList())?.let { asset ->
|
||||
r.optBoolean("prerelease") to Release(r.optString("tag_name", asset), r.optString("published_at"), asset, byName.getValue(asset))
|
||||
r.optBoolean("prerelease") to byName.getValue(asset).let { a ->
|
||||
Release(r.optString("tag_name", asset), r.optString("published_at"), asset, a.getString("browser_download_url"),
|
||||
Hashes.githubSha256(a.optString("digest")))
|
||||
}
|
||||
}
|
||||
}
|
||||
val pick = (candidates.firstOrNull { !it.first } ?: candidates.firstOrNull())?.second
|
||||
@@ -331,7 +335,7 @@ object UserApps {
|
||||
val download = File(context.cacheDir, "github-${release.asset}")
|
||||
try {
|
||||
val label = context.getString(R.string.user_apps_downloading, release.asset)
|
||||
val ok = Downloader.downloadFile(release.url, download, false) { f -> onProgress(label, if (f < 0) -1 else Math.round(f * 100f)) }
|
||||
val ok = Downloader.downloadFile(release.url, download, false, release.sha256) { f -> onProgress(label, if (f < 0) -1 else Math.round(f * 100f)) }
|
||||
return if (ok) use(download) else context.getString(R.string.user_apps_download_failed)
|
||||
} finally {
|
||||
download.delete()
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
@@ -714,7 +714,9 @@ class SessionService : Service() {
|
||||
private fun addControllerEnvironment(guest: MutableList<String>, fakeInputDir: File, sessionDir: File) {
|
||||
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
|
||||
val builtinPad = SessionPrefs.builtinPad(this)
|
||||
val hiddenPad = SessionState.mode == MODE_STEAM && !builtinPad
|
||||
val hiddenPad = SessionState.mode == MODE_STEAM && !builtinPad &&
|
||||
!com.droiddeck.launcher.input.PadBridge.anyControllerConnected()
|
||||
com.droiddeck.launcher.input.PadBridge.setFirstSlot(if (hiddenPad) 1 else 0)
|
||||
fakeInputDir.listFiles()?.forEach { file ->
|
||||
val node = Regex("event(\\d+)").matchEntire(file.name)?.groupValues?.get(1)?.toIntOrNull()
|
||||
if (file.name.startsWith(".uinput-") || (node != null && node >= FIRST_VIRTUAL_PAD) ||
|
||||
|
||||
@@ -369,7 +369,9 @@ object WinComponents {
|
||||
val archiveName = archive.optString("name")
|
||||
val url = c.snapshot.substringBeforeLast('/') + "/" + archiveName
|
||||
val file = File(work, "${c.name}.files.tar.xz")
|
||||
if (!Downloader.downloadFile(url, file, false) { f -> onProgress(Progress(c.name, archiveName, Phase.DOWNLOAD, if (f < 0) -1 else Math.round(f * 100f))) }) {
|
||||
// The snapshot came straight from github.com, so its digest may vouch for a mirror's copy of the archive.
|
||||
val sha = archive.optString("sha256").takeIf { it.matches(Regex("(?i)[0-9a-f]{64}")) }
|
||||
if (!Downloader.downloadFile(url, file, false, sha) { f -> onProgress(Progress(c.name, archiveName, Phase.DOWNLOAD, if (f < 0) -1 else Math.round(f * 100f))) }) {
|
||||
return null to "download failed: $archiveName"
|
||||
}
|
||||
archive.optString("sha256").takeIf { it.length == 64 }?.let { sha ->
|
||||
|
||||
@@ -315,7 +315,7 @@ internal fun AppDialog(
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.fillMaxSize().imePadding()
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = close),
|
||||
.tapOutside(close),
|
||||
) {
|
||||
AnimatedVisibility(
|
||||
visibleState = shown,
|
||||
@@ -340,7 +340,7 @@ internal fun AppDialog(
|
||||
.clip(Shape16)
|
||||
.background(pal.surfaceVariant.copy(alpha = 0.97f))
|
||||
.border(1.dp, pal.signal.copy(alpha = 0.22f), Shape16)
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}
|
||||
.blockTouches()
|
||||
.controllerBack(back ?: close)
|
||||
.then(modifier)
|
||||
.then(if (scrollable) Modifier.verticalScroll(rememberScrollState()) else Modifier)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -52,6 +52,7 @@ import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
@@ -142,8 +143,13 @@ internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
|
||||
PrimaryButton(open, enabled = !s.busy, main = true, large = true, icon = Icons.Outlined.DesktopWindows, onClick = click)
|
||||
},
|
||||
beside = {
|
||||
HeroIconButton(Icons.Outlined.Storefront, stringResource(R.string.flathub_name), FlathubTeal, "desktop:flathub") { at -> openFrom(at, null, "store") }
|
||||
HeroIconButton(Icons.Filled.Add, stringResource(R.string.user_apps_add), null, "desktop:add") { if (!s.busy) adding = true }
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
HeroIconButton(Icons.Outlined.Storefront, stringResource(R.string.flathub_name), FlathubTeal, "desktop:flathub") { at -> openFrom(at, null, "store") }
|
||||
HeroIconButton(Icons.Filled.Add, stringResource(R.string.user_apps_add), null, "desktop:add") { if (!s.busy) adding = true }
|
||||
}
|
||||
if (s.desktopPresent) UninstallDesktop(enabled = !s.runtimeActionsBlocked, onUninstall = a.onRemoveDesktop)
|
||||
}
|
||||
},
|
||||
rows = { tab ->
|
||||
if (tab == SheetTab.FILES) DesktopFiles(s, a)
|
||||
@@ -366,6 +372,7 @@ private fun DesktopFiles(s: FrontEndState, a: FrontEndActions) {
|
||||
|
||||
@Composable
|
||||
private fun UninstallDesktop(enabled: Boolean, onUninstall: () -> Unit) {
|
||||
val canUninstall by rememberUpdatedState(enabled)
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val label = stringResource(R.string.common_uninstall)
|
||||
val title = stringResource(R.string.desktop_uninstall_title)
|
||||
@@ -383,7 +390,7 @@ private fun UninstallDesktop(enabled: Boolean, onUninstall: () -> Unit) {
|
||||
Text(note, fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.stepItem(1).padding(start = 4.dp, bottom = 12.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), modifier = Modifier.fillMaxWidth().stepItem(2)) {
|
||||
StepChoice(keep, enabled = open, modifier = Modifier.focusRequester(first)) { Steps.fold() }
|
||||
StepChoice(label, danger = true, enabled = open) { Steps.fold(); onUninstall() }
|
||||
StepChoice(label, danger = true, enabled = open && canUninstall) { Steps.fold(); onUninstall() }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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) }
|
||||
|
||||
@@ -221,7 +221,7 @@ fun LoadingOverlay(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(colors.background)
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {},
|
||||
.blockTouches(),
|
||||
) {
|
||||
CapsuleWall(games, driftMs = 65_000, modifier = Modifier.alpha(0.3f))
|
||||
Box(
|
||||
@@ -350,7 +350,6 @@ private fun CancelHint(onCancel: () -> Unit, modifier: Modifier = Modifier) {
|
||||
fun SessionPausedOverlay(title: String = stringResource(R.string.load_steam_paused), onResume: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
val resumeFocus = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
@@ -360,7 +359,7 @@ fun SessionPausedOverlay(title: String = stringResource(R.string.load_steam_paus
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(pal.background.copy(alpha = 0.94f))
|
||||
.clickable(interactionSource = interactionSource, indication = null) {},
|
||||
.blockTouches(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Column(
|
||||
|
||||
@@ -103,6 +103,7 @@ import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
@@ -312,7 +313,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
|
||||
@@ -384,10 +385,15 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
focus.request(first)
|
||||
}
|
||||
}
|
||||
if (open || veil > 0.01f) Box(
|
||||
modifier = Modifier.fillMaxSize()
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { host.open = null; a.onClose() },
|
||||
)
|
||||
if (open || veil > 0.01f) {
|
||||
val closeLabel = stringResource(R.string.common_close)
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize()
|
||||
.focusProperties { canFocus = false }
|
||||
.semantics { contentDescription = closeLabel }
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClickLabel = closeLabel) { host.open = null; a.onClose() },
|
||||
)
|
||||
}
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) {
|
||||
val short = maxHeight < 440.dp
|
||||
val sheetWidth = minOf(360.dp, maxWidth * 0.92f)
|
||||
@@ -401,7 +407,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(pal.background.copy(alpha = 0.97f))
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}
|
||||
.blockTouches()
|
||||
.focusGroup()
|
||||
.controllerBack {
|
||||
if (host.open != null) host.open = null else a.onClose()
|
||||
|
||||
@@ -34,7 +34,9 @@ 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.detectTapGestures
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
@@ -141,6 +143,11 @@ internal fun Modifier.controllerBack(onBack: () -> Unit): Modifier = onPreviewKe
|
||||
}
|
||||
}
|
||||
|
||||
internal fun Modifier.blockTouches(): Modifier = pointerInput(Unit) { detectTapGestures { } }
|
||||
|
||||
internal fun Modifier.tapOutside(onTap: () -> Unit): Modifier =
|
||||
pointerInput(onTap) { detectTapGestures(onTap = { onTap() }) }
|
||||
|
||||
internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modifier = onPreviewKeyEvent { event ->
|
||||
val keyEvent = event.nativeKeyEvent
|
||||
val previous = keyEvent.keyCode == KeyEvent.KEYCODE_BUTTON_L1
|
||||
|
||||
@@ -303,7 +303,7 @@ internal fun SessionAchievementsPanel(label: String, state: AchievementsState, t
|
||||
val slide = remember { MutableTransitionState(false).apply { targetState = true } }
|
||||
BoxWithConstraints(
|
||||
Modifier.fillMaxSize().background(veil)
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onClose),
|
||||
.tapOutside(onClose),
|
||||
contentAlignment = Alignment.CenterEnd,
|
||||
) {
|
||||
val short = maxHeight < 440.dp
|
||||
@@ -312,7 +312,7 @@ internal fun SessionAchievementsPanel(label: String, state: AchievementsState, t
|
||||
(if (floating) Modifier.padding(12.dp).fillMaxHeight().width(minOf(420.dp, maxWidth * 0.92f)).clip(RoundedCornerShape(20.dp))
|
||||
.background(pal.background).border(1.dp, pal.line2, RoundedCornerShape(20.dp))
|
||||
else Modifier.fillMaxHeight().width(minOf(420.dp, maxWidth * 0.92f)).background(pal.background.copy(alpha = 0.97f)))
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}
|
||||
.blockTouches()
|
||||
.controllerBack(onClose)
|
||||
.then(if (kinds.isEmpty()) Modifier else Modifier.bumpers({ pick = (pick + kinds.size - 1) % kinds.size }, { pick = (pick + 1) % kinds.size }))
|
||||
.padding(if (short) 12.dp else 16.dp),
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user