diff --git a/.github/workflows/authorship.yml b/.github/workflows/authorship.yml new file mode 100644 index 0000000000..97c6637a8f --- /dev/null +++ b/.github/workflows/authorship.yml @@ -0,0 +1,40 @@ +name: Build validation + +on: + pull_request_target: + branches: [main] + types: [opened, synchronize, reopened, edited, ready_for_review] + push: + branches: [main] + workflow_run: + workflows: [Build APK] + types: [completed] + workflow_dispatch: + inputs: + pr_number: + description: Pull request to validate; empty for main + required: false + +permissions: + contents: read + actions: read + pull-requests: read + statuses: write + +jobs: + validate: + name: Build APK + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.workflow_sha }} + fetch-depth: 0 + persist-credentials: false + - name: Validate source and APK compilation + env: + GH_TOKEN: ${{ github.token }} + run: | + gh auth setup-git + python3 tools/release/validate_apk.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0dc1289e59..aacad45f03 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -87,7 +87,7 @@ jobs: build: needs: xbox - name: Build APK + name: Compile and test APK if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} runs-on: ubuntu-24.04 timeout-minutes: 45 @@ -100,17 +100,22 @@ jobs: fetch-depth: 0 persist-credentials: false - - name: Check co-authors - if: github.event_name == 'pull_request' + - name: Check human authorship + env: + EVENT_NAME: ${{ github.event_name }} + BEFORE: ${{ github.event.before }} run: | set -euo pipefail - git fetch --no-tags origin main - base=$(git merge-base origin/main HEAD) - messages=$(git log --format=%B "$base..HEAD") - messages+=$'\n'"$(jq -r '.pull_request.title, (.pull_request.body // "")' "$GITHUB_EVENT_PATH")" - if grep -Eiq '^[[:space:]]*Co-authored-by:.*(Claude|Anthropic|OpenAI|ChatGPT|GPT|Copilot|Cursor|Gemini|Codex|Devin|Windsurf|Codeium|Amazon Q|Tabnine|Cody|\[bot\])' <<<"$messages"; then - echo "::error::AI and bot identities cannot be co-authors; remove the Co-authored-by trailer." - exit 1 + if [ "$EVENT_NAME" = pull_request ]; then + git fetch --no-tags origin main + base=$(git merge-base origin/main HEAD) + checker="$RUNNER_TEMP/droiddeck-check-authorship.py" + git show origin/main:tools/release/check_authorship.py > "$checker" + python3 "$checker" "$base..HEAD" --event "$GITHUB_EVENT_PATH" + elif [ "$EVENT_NAME" = push ] && [ "$BEFORE" != 0000000000000000000000000000000000000000 ]; then + python3 tools/release/check_authorship.py "$BEFORE..HEAD" + else + python3 tools/release/check_authorship.py HEAD fi - name: The packages a signed build ships as diff --git a/app/src/main/assets/licenses/viture-v2/LICENSE b/app/src/main/assets/licenses/viture-v2/LICENSE new file mode 100644 index 0000000000..9c1d9de29a --- /dev/null +++ b/app/src/main/assets/licenses/viture-v2/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Holger Bartnick + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/app/src/main/cpp/fakeinput_steam.cpp b/app/src/main/cpp/fakeinput_steam.cpp index 05d0138dde..c446170fe9 100644 --- a/app/src/main/cpp/fakeinput_steam.cpp +++ b/app/src/main/cpp/fakeinput_steam.cpp @@ -2650,6 +2650,38 @@ __attribute__((visibility("hidden"))) static int triton_get_feature(DeckHidraw & static constexpr uint32_t TRITON_HWID = 72; static constexpr uint32_t TRITON_FW_TIMESTAMP = 0x6AC686B3; +// Steam compares the controller's firmware with TRITON_FW_TS in its bundled hardwareupdater.cfg (and blocks +// with a required update below MUST_UPDATE_TRITON_FW_TS), so the emulated pad reports at least the build +// Steam ships. +static uint32_t triton_fw_timestamp() { + static const uint32_t timestamp = [] { + std::vector roots; + char exe[PATH_MAX]; + ssize_t n = readlink("/proc/self/exe", exe, sizeof(exe) - 1); + if (n > 0) { + std::string path(exe, static_cast(n)); + size_t bin = path.rfind('/'); + size_t root = bin == std::string::npos || bin == 0 ? std::string::npos : path.rfind('/', bin - 1); + if (bin != std::string::npos && bin > 0) roots.push_back(path.substr(0, bin)); + if (root != std::string::npos) roots.push_back(path.substr(0, root)); + } + if (const char *home = getenv("HOME")) roots.push_back(std::string(home) + "/.local/share/Steam"); + uint32_t newest = TRITON_FW_TIMESTAMP; + for (const std::string &root : roots) { + std::ifstream cfg(root + "/bin/hardwareupdater/hardwareupdater.cfg"); + std::string line; + while (std::getline(cfg, line)) { + if (line.rfind("TRITON_FW_TS:", 0) != 0) continue; + uint32_t shipped = static_cast(strtoul(line.c_str() + 13, nullptr, 16)); + if (shipped > newest) newest = shipped; + } + } + if (newest != TRITON_FW_TIMESTAMP) Logger::log("triton: reporting firmware %08x, the build Steam ships\n", newest); + return newest; + }(); + return timestamp; +} + __attribute__((visibility("hidden"))) static int triton_pad_feature(DeckHidraw &triton, uint8_t *buf, size_t size, bool set) { if (!buf || size < 2) { errno = EINVAL; @@ -2670,7 +2702,7 @@ __attribute__((visibility("hidden"))) static int triton_pad_feature(DeckHidraw & switch (triton.pending_feature) { case DECK_GET_ATTRIBUTES_VALUES: { static const uint8_t kIds[] = {0x01, 0x02, 0x04, 0x09, 0x0a, 0x0b}; - const uint32_t values[] = {static_cast(TRITON_WIRED_PRODUCT), 0, TRITON_FW_TIMESTAMP, TRITON_HWID, 0, 4000}; + const uint32_t values[] = {static_cast(TRITON_WIRED_PRODUCT), 0, triton_fw_timestamp(), TRITON_HWID, 0, 4000}; reply[2] = sizeof(kIds) * 5; for (size_t i = 0; i < sizeof(kIds); i++) { reply[3 + i * 5] = kIds[i]; diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index 68df13b2c1..3fc4383772 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -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) diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt index 89530f437a..19cba0c8bb 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -1639,6 +1639,7 @@ class MainActivity : ComponentActivity() { pipAutoEnter = pipAutoEnter, unfoldedControls = if (mode == SessionService.MODE_STEAM && com.droiddeck.launcher.session.SessionDisplay.foldable(this)) unfoldedControls else null, + unfoldedControlsWithController = unfoldedControlsWithController, oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null, backActionsInverted = backActionsInverted, directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null, @@ -1705,6 +1706,9 @@ class MainActivity : ComponentActivity() { onZramCompression = { on -> SessionPrefs.setZramCompression(this, on); zramCompression = on }, onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this, on); pipAutoEnter = on }, onUnfoldedControls = { on -> SessionPrefs.setUnfoldedControls(this, on); unfoldedControls = on }, + onUnfoldedControlsWithController = { on -> + SessionPrefs.setUnfoldedControlsWithController(this, on); unfoldedControlsWithController = on + }, onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o }, onBackActionsInverted = { inverted -> SessionPrefs.setBackActionsInverted(this, inverted) @@ -1893,10 +1897,12 @@ class MainActivity : ComponentActivity() { private var pipAutoEnter by mutableStateOf(false) private var unfoldedControls by mutableStateOf(false) + private var unfoldedControlsWithController by mutableStateOf(false) private fun loadModeSettings(mode: String) { pipAutoEnter = SessionPrefs.pipAutoEnter(this) unfoldedControls = SessionPrefs.unfoldedControls(this) + unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this) resolution = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) fexPreset = SessionPrefs.fexPreset(this) forceSsbs = SessionPrefs.forceSsbs(this) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index f43a272869..6de07a00dc 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -134,6 +134,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private var pipUi by mutableStateOf(false) private var pipAutoEnter by mutableStateOf(false) private var unfoldedControls by mutableStateOf(false) + private var unfoldedControlsWithController by mutableStateOf(false) private var picturePosition by mutableStateOf("center") private fun applyGameAlignment() { @@ -366,17 +367,46 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private var secondScreenDisplays by mutableStateOf>(emptyList()) private var selectedSecondScreenDisplay by mutableStateOf(SessionState.secondScreenDisplay) private var started = false + private var sessionActivityDisplayId = Display.DEFAULT_DISPLAY private lateinit var displayManager: DisplayManager private var secondScreenPresentation: SecondScreenPresentation? = null private val displayListener = object : DisplayManager.DisplayListener { - override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays() - override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays() + override fun onDisplayAdded(displayId: Int) { + notifyActivityDisplayStateChanged(displayId) + refreshSecondScreenDisplays() + } + override fun onDisplayRemoved(displayId: Int) { + if (refreshActivityDisplayId() && started) { + SessionService.setActivityDisplay(this@SessionActivity, sessionActivityDisplayId) + } + refreshSecondScreenDisplays() + } override fun onDisplayChanged(displayId: Int) { + notifyActivityDisplayStateChanged(displayId) followPanelRefresh(displayId) refreshSecondScreenDisplays() } } + @Suppress("DEPRECATION") + private fun currentActivityDisplayId(): Int = windowManager.defaultDisplay.displayId + + private fun refreshActivityDisplayId(): Boolean { + val current = if (Build.VERSION.SDK_INT >= 30) display?.displayId ?: currentActivityDisplayId() + else currentActivityDisplayId() + val changed = sessionActivityDisplayId != current + sessionActivityDisplayId = current + SessionState.activityDisplayId = current + return changed + } + + private fun notifyActivityDisplayStateChanged(changedDisplayId: Int) { + val changed = refreshActivityDisplayId() + if (started && (changed || changedDisplayId == sessionActivityDisplayId)) { + SessionService.setActivityDisplay(this, sessionActivityDisplayId) + } + } + private fun followPanelRefresh(displayId: Int) { if (!CompositorHost.isStarted) return val output = glassesScreen?.display @@ -923,6 +953,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { }, unfoldedControls = if (com.droiddeck.launcher.session.SessionDisplay.foldable(this@SessionActivity)) unfoldedControls else null, onUnfoldedControls = ::chooseUnfoldedControls, + unfoldedControlsWithController = unfoldedControlsWithController, + onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController, onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) }, onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() }, onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() }, @@ -1407,6 +1439,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun readPrefs() { pipAutoEnter = SessionPrefs.pipAutoEnter(this) unfoldedControls = SessionPrefs.unfoldedControls(this) + unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this) picturePosition = SessionPrefs.picturePosition(this) hudOn = SessionPrefs.hudEnabled(this) hudFps = SessionPrefs.hudShowFps(this) @@ -1678,7 +1711,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { intent.getStringExtra(SessionService.EXTRA_STEAM_UI), intent.getStringExtra(SessionService.EXTRA_STEAM_URL), intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS), - shownOnDisplayId, + sessionActivityDisplayId, ) } applyFrameGen() @@ -1729,7 +1762,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onConfigurationChanged(newConfig: android.content.res.Configuration) { super.onConfigurationChanged(newConfig) - if (started) SessionService.setActivityDisplay(this, shownOnDisplayId) + if (refreshActivityDisplayId() && started) { + SessionService.setActivityDisplay(this, sessionActivityDisplayId) + } cancelTouchGestures() applyFollowOrientation(newConfig) applyUnfoldedControls() @@ -2456,6 +2491,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { applyUnfoldedControls() } + private fun chooseUnfoldedControlsWithController(on: Boolean) { + SessionPrefs.setUnfoldedControlsWithController(this, on) + unfoldedControlsWithController = on + applyUnfoldedControls() + } + private fun refreshControls() { applyUnfoldedControls() updateOnScreenControls() @@ -2465,11 +2506,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (!::sessionRoot.isInitialized) return val width = sessionRoot.width val height = sessionRoot.height - val wanted = unfoldedControls && com.droiddeck.launcher.session.SessionDisplay.foldable(this) && - !PadBridge.anyControllerConnected() && !SteamControllerBle.connected && - SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad && - !pipUi && !isInPictureInPictureMode && width > 0 && height > 0 && - resources.configuration.smallestScreenWidthDp >= com.droiddeck.launcher.session.SessionDisplay.UNFOLDED_MIN_DP + val wanted = com.droiddeck.launcher.session.SessionDisplay.unfoldedControlsWanted( + enabled = unfoldedControls, + foldable = com.droiddeck.launcher.session.SessionDisplay.foldable(this), + controllerConnected = PadBridge.anyControllerConnected() || SteamControllerBle.connected, + keepWithController = unfoldedControlsWithController, + steamDeckPad = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad, + pip = pipUi || isInPictureInPictureMode, + width = width, + height = height, + smallestWidthDp = resources.configuration.smallestScreenWidthDp, + ) val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height) else FrameLayout.LayoutParams.MATCH_PARENT val params = surfaceView.layoutParams as FrameLayout.LayoutParams @@ -2888,11 +2935,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { super.onStart() if (runtimeRemovalBlocked) return started = true + refreshActivityDisplayId() displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper())) refreshSecondScreenDisplays() if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode) startedScreens++ - SessionService.setActivityVisible(this, true, shownOnDisplayId) + SessionService.setActivityVisible(this, true, sessionActivityDisplayId) Glasses.rescan() updateGlassesScreen() updateHandCamera() @@ -2906,7 +2954,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { closeSecondScreen(reset = false) startedScreens = (startedScreens - 1).coerceAtLeast(0) updateGlassesScreen() - if (startedScreens == 0) SessionService.setActivityVisible(this, false) + if (startedScreens == 0) SessionService.setActivityVisible(this, false, sessionActivityDisplayId) super.onStop() } @@ -2937,6 +2985,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onResume() { super.onResume() + if (refreshActivityDisplayId() && started) { + SessionService.setActivityDisplay(this, sessionActivityDisplayId) + } applyFollowOrientation(resources.configuration) if (runtimeRemovalBlocked) return com.droiddeck.launcher.ui.Motion.refresh(this) @@ -3418,7 +3469,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun finishFlooded() { if (isFinishing) return - val signal = com.droiddeck.launcher.ui.Themes.byId(SessionPrefs.theme(this)).signal + val signal = com.droiddeck.launcher.ui.Themes.current(this).signal com.droiddeck.launcher.ui.QuitFlood.mark(signal.toArgb()) window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(signal.toArgb())) quitFlooded = true @@ -3449,7 +3500,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun completeLeave() { if (isFinishing) return - val signal = com.droiddeck.launcher.ui.Themes.byId(SessionPrefs.theme(this)).signal + val signal = com.droiddeck.launcher.ui.Themes.current(this).signal com.droiddeck.launcher.ui.QuitFlood.mark(signal.toArgb()) window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(signal.toArgb())) quitFlooded = true diff --git a/app/src/main/java/com/droiddeck/launcher/files/CollapsibleRail.kt b/app/src/main/java/com/droiddeck/launcher/files/CollapsibleRail.kt index 665d063fd5..bcba0189bd 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/CollapsibleRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/CollapsibleRail.kt @@ -6,6 +6,7 @@ import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -249,11 +250,11 @@ fun CollapsibleRail( if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f), shape, ) - .clickable(onClick = item.onClick) + .clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick) .padding(horizontal = if (collapsed) 2.dp else 11.dp, vertical = if (collapsed) 6.dp else 9.dp) } else { base - .clickable(onClick = item.onClick) + .clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick) .background(if (active) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent) .padding(horizontal = if (collapsed) 2.dp else 13.dp, vertical = if (collapsed) 7.dp else 11.dp) } @@ -337,7 +338,7 @@ fun RailTopTabs( .background(MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)), ) links.forEach { link -> - TopTabCell(link.icon, link.label, selected = false, onClick = link.onClick, modifier = Modifier.weight(1f)) + TopTabCell(link.icon, link.label, selected = false, onClick = link.onClick, isTab = false, modifier = Modifier.weight(1f)) } } } @@ -352,6 +353,7 @@ private fun TopTabCell( selected: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, + isTab: Boolean = true, ) { val tint = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant Column( @@ -359,7 +361,13 @@ private fun TopTabCell( modifier = modifier .clip(RoundedCornerShape(9.dp)) .background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent) - .clickable(onClick = onClick) + .then( + if (isTab) { + Modifier.selectable(selected = selected, role = androidx.compose.ui.semantics.Role.Tab, onClick = onClick) + } else { + Modifier.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onClick) + }, + ) .padding(vertical = 6.dp, horizontal = 1.dp), ) { Icon(icon, contentDescription = label, tint = tint, modifier = Modifier.size(20.dp)) diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt index 45c8a92c83..e6289a3b98 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt @@ -193,7 +193,7 @@ internal fun FileItemRow( modifier = Modifier .fillMaxWidth() .padding(horizontal = 12.dp, vertical = 3.dp) - .combinedClickable( + .combinedClickable(role = androidx.compose.ui.semantics.Role.Button, onClick = { if (selectionMode) onToggleSelect() else onTap() }, onLongClick = onLongPress, ), @@ -302,7 +302,7 @@ internal fun ParentFolderRow(compact: Boolean = false, onTap: () -> Unit) { modifier = Modifier .fillMaxWidth() .padding(horizontal = 12.dp, vertical = 3.dp) - .clickable(onClick = onTap), + .clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onTap), shape = RoundedCornerShape(10.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer), border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline), @@ -422,7 +422,7 @@ private fun FavoriteCard( modifier = Modifier .fillMaxWidth() .padding(horizontal = 12.dp, vertical = 3.dp) - .clickable(onClick = onJump), + .clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onJump), shape = RoundedCornerShape(10.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer), border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline), @@ -526,7 +526,7 @@ internal fun FileGridTile( Card( modifier = Modifier .padding(4.dp) - .combinedClickable( + .combinedClickable(role = androidx.compose.ui.semantics.Role.Button, onClick = { if (selectionMode) onToggleSelect() else onTap() }, onLongClick = onLongPress, ), diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/Glasses.kt b/app/src/main/java/com/droiddeck/launcher/glasses/Glasses.kt index 947ed5fd27..fe09a7809e 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/Glasses.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/Glasses.kt @@ -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 { diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/GlassesHardware.kt b/app/src/main/java/com/droiddeck/launcher/glasses/GlassesHardware.kt index 7362ebf44a..5de0f03f52 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/GlassesHardware.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/GlassesHardware.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/VitureProtocol.kt b/app/src/main/java/com/droiddeck/launcher/glasses/VitureProtocol.kt index 4d3147d65d..573f0f8dcf 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/VitureProtocol.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/VitureProtocol.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/VitureV2Link.kt b/app/src/main/java/com/droiddeck/launcher/glasses/VitureV2Link.kt new file mode 100644 index 0000000000..d46c246b7c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/glasses/VitureV2Link.kt @@ -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(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() + + 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 + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/VitureV2Protocol.kt b/app/src/main/java/com/droiddeck/launcher/glasses/VitureV2Protocol.kt new file mode 100644 index 0000000000..548ad6b918 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/glasses/VitureV2Protocol.kt @@ -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() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/DeviceInfo.kt b/app/src/main/java/com/droiddeck/launcher/gpu/DeviceInfo.kt index 48c58d01be..9a5fb11821 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/DeviceInfo.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/DeviceInfo.kt @@ -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 %" }) diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt index adfa2589a5..652d33fbe0 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt @@ -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 { + 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 ?: "" diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt b/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt index 39ad3f2ab2..c1f2966b6d 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt @@ -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) diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java index 6fb7360f3e..9978409c5f 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java +++ b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java @@ -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; } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt index ae64b98cf0..c0bba60936 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt @@ -44,6 +44,19 @@ object SessionDisplay { fun unfoldedGameHeight(width: Int, height: Int): Int = minOf(width * 9 / 16, (height * UNFOLDED_MAX_GAME_SHARE).toInt()) and 1.inv() + fun unfoldedControlsWanted( + enabled: Boolean, + foldable: Boolean, + controllerConnected: Boolean, + keepWithController: Boolean, + steamDeckPad: Boolean, + pip: Boolean, + width: Int, + height: Int, + smallestWidthDp: Int, + ): Boolean = enabled && foldable && (keepWithController || !controllerConnected) && steamDeckPad && + !pip && width > 0 && height > 0 && smallestWidthDp >= UNFOLDED_MIN_DP + fun panelSize(context: Context): Pair { val manager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 6158713f81..0dab068d85 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -213,6 +213,7 @@ object SessionFiles { if (!FileUtils.writeString(File(etc, "steam-compatibility-label"), context.getString(R.string.steam_compat_label))) { Log.e(TAG, "could not write steam-compatibility-label") } + writeCjkFontConfig(root, etc) val droiddeckEtc = File(etc, "droiddeck").apply { mkdirs() } val stagedSocket = File(droiddeckEtc, "bwrap-socket.staged") if (!FileUtils.writeString(stagedSocket, BwrapSpawner.socket(context) + "\n") @@ -554,4 +555,96 @@ object SessionFiles { ).joinToString(newline) fun logDirectory(context: Context): File = LinuxRuntime.logDir(context).apply { mkdirs() } + + /** + * Registers the Android system fonts (which include CJK faces such as Noto Sans CJK / + * MiSans) with the container's fontconfig, so the Steam Deck UI (CEF/webkit renderer) + * resolves Chinese/Japanese glyphs instead of showing tofu / mojibake. + * The fonts themselves are bind-mounted by LinuxRuntime.bindSystemFonts() into + * /usr/local/share/fonts/android; here we only need to point fontconfig at them. + */ + private fun writeCjkFontConfig(root: File, etc: File) { + try { + val confDir = File(etc, "fonts/conf.d").apply { mkdirs() } + val conf = File(confDir, "99-droiddeck-cjk.conf") + val xml = """ + + + /usr/local/share/fonts/android + /system/fonts + + ja + sans-serif + Noto Sans CJK JP + + + ja + serif + Noto Serif CJK JP + + + zh + sans-serif + Noto Sans CJK SC + + + zh + serif + Noto Serif CJK SC + + + zh-cn + sans-serif + Noto Sans CJK SC + + + zh-cn + serif + Noto Serif CJK SC + + + zh-tw + sans-serif + Noto Sans CJK TC + + + zh-tw + serif + Noto Serif CJK TC + + + zh-hk + sans-serif + Noto Sans CJK TC + + + zh-hk + serif + Noto Serif CJK TC + + + ko + sans-serif + Noto Sans CJK KR + + + ko + serif + Noto Serif CJK KR + + +""" + if (!conf.isFile || FileUtils.readString(conf) != xml) { + val staged = File(confDir, conf.name + ".staged") + if (FileUtils.writeString(staged, xml) && staged.renameTo(conf)) { + Log.i(TAG, "Wrote CJK fontconfig 99-droiddeck-cjk.conf") + } else { + staged.delete() + Log.e(TAG, "Could not write CJK fontconfig") + } + } + } catch (e: Exception) { + Log.w(TAG, "CJK fontconfig setup failed", e) + } + } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 1bf65ecb63..aa057eb475 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -816,6 +816,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 = 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? = parseResolution(prefs(context).getString("customRes.$mode", null)) @@ -1036,6 +1046,13 @@ object SessionPrefs { prefs(context).edit().putBoolean("unfoldedControls", enabled).apply() } + fun unfoldedControlsWithController(context: Context): Boolean = + prefs(context).getBoolean("unfoldedControlsWithController", false) + + fun setUnfoldedControlsWithController(context: Context, enabled: Boolean) { + prefs(context).edit().putBoolean("unfoldedControlsWithController", enabled).apply() + } + const val SURFACE_STICK = "stick" const val SURFACE_TRACKPAD = "trackpad" diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 6ca5dc5496..d4782c191f 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -76,9 +76,16 @@ class SessionService : Service() { private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL private var steamDownloadsInBackground = false private var activityVisible = true + private var activityDisplayId = Display.DEFAULT_DISPLAY private var xrActivityVisible = false private var signInHold = false - private val hasVisibleSurface get() = sessionHasVisibleSurface(activityVisible || signInHold, screenOn, xrActivityVisible) + private val hasVisibleSurface get() = !SessionVisibilityPolicy.isHidden( + activityStarted = activityVisible || signInHold, + defaultDisplayOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn, + activityOnDefaultDisplay = activityDisplayId == Display.DEFAULT_DISPLAY, + activityDisplayOn = activityDisplayOn(), + xrActivityVisible = xrActivityVisible, + ) private var screenOn = true private var sessionDisplayId = Display.DEFAULT_DISPLAY private var manualPauseRequested = false @@ -115,12 +122,22 @@ class SessionService : Service() { private val displayListener = object : DisplayManager.DisplayListener { override fun onDisplayAdded(displayId: Int) {} override fun onDisplayRemoved(displayId: Int) { - if (displayId != sessionDisplayId) return - sessionDisplayId = Display.DEFAULT_DISPLAY - refreshScreenOn() + if (displayId == sessionDisplayId) { + sessionDisplayId = Display.DEFAULT_DISPLAY + refreshScreenOn() + } + if (displayId == activityDisplayId) { + suspendAttemptFailed = false + updateSuspendPolicy() + } } override fun onDisplayChanged(displayId: Int) { if (displayId == sessionDisplayId && displayId != Display.DEFAULT_DISPLAY) refreshScreenOn() + if (displayId == activityDisplayId) { + resumeSteamSleepOnReturn() + suspendAttemptFailed = false + updateSuspendPolicy() + } } } @@ -132,6 +149,14 @@ class SessionService : Service() { interactive ?: (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: true, state) } + private fun activityDisplayOn(): Boolean { + if (activityDisplayId == Display.DEFAULT_DISPLAY) { + return (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn + } + val displays = getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager ?: return false + return displays.getDisplay(activityDisplayId)?.state == Display.STATE_ON + } + private fun refreshScreenOn() { val on = readScreenOn() if (on == screenOn) return @@ -202,6 +227,7 @@ class SessionService : Service() { ACTION_ACTIVITY_VISIBLE -> { if (!SessionState.pipActive) pipTask = false activityVisible = true + activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId) sessionDisplayId = intent.getIntExtra(EXTRA_DISPLAY_ID, sessionDisplayId) screenOn = readScreenOn() suspendDownloadNow = false @@ -215,8 +241,16 @@ class SessionService : Service() { refreshScreenOn() return START_NOT_STICKY } + ACTION_ACTIVITY_DISPLAY_CHANGED -> { + activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId) + resumeSteamSleepOnReturn() + suspendAttemptFailed = false + updateSuspendPolicy() + return START_NOT_STICKY + } ACTION_ACTIVITY_HIDDEN -> { activityVisible = false + activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId) suspendAttemptFailed = false updateSuspendPolicy() return START_NOT_STICKY @@ -279,6 +313,7 @@ class SessionService : Service() { xrActivityVisible = false signInHold = false sessionDisplayId = intent?.getIntExtra(EXTRA_DISPLAY_ID, Display.DEFAULT_DISPLAY) ?: Display.DEFAULT_DISPLAY + activityDisplayId = intent?.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, sessionDisplayId) ?: sessionDisplayId screenOn = readScreenOn() manualPauseRequested = false suspendDownloadNow = false @@ -1843,7 +1878,9 @@ class SessionService : Service() { private const val ACTION_ACTIVITY_VISIBLE = "com.droiddeck.launcher.ACTIVITY_VISIBLE" private const val ACTION_ACTIVITY_HIDDEN = "com.droiddeck.launcher.ACTIVITY_HIDDEN" private const val ACTION_ACTIVITY_DISPLAY = "com.droiddeck.launcher.ACTIVITY_DISPLAY" + private const val ACTION_ACTIVITY_DISPLAY_CHANGED = "com.droiddeck.launcher.ACTIVITY_DISPLAY_CHANGED" private const val EXTRA_DISPLAY_ID = "displayId" + private const val EXTRA_ACTIVITY_DISPLAY_ID = "activityDisplayId" private const val ACTION_XR_ACTIVITY_VISIBLE = "com.droiddeck.launcher.XR_ACTIVITY_VISIBLE" private const val ACTION_XR_ACTIVITY_HIDDEN = "com.droiddeck.launcher.XR_ACTIVITY_HIDDEN" private const val ACTION_SIGN_IN_HOLD = "com.droiddeck.launcher.SIGN_IN_HOLD" @@ -1888,8 +1925,10 @@ class SessionService : Service() { steamUi: String? = null, steamUrl: String? = null, programArgs: Array? = null, displayId: Int = Display.DEFAULT_DISPLAY, ) { + SessionState.activityDisplayId = displayId val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode) .putExtra(EXTRA_DISPLAY_ID, displayId) + .putExtra(EXTRA_ACTIVITY_DISPLAY_ID, displayId) if (program != null) intent.putExtra(EXTRA_PROGRAM, program) if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs) if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi) @@ -1910,15 +1949,29 @@ class SessionService : Service() { context.startService(Intent(context, SessionService::class.java).setAction(ACTION_PIP_BEGIN)) } - fun setActivityVisible(context: Context, visible: Boolean, displayId: Int = Display.DEFAULT_DISPLAY) { + fun setActivityVisible(context: Context, visible: Boolean, displayId: Int = contextDisplayId(context)) { if (!SessionState.running) return val action = if (visible) ACTION_ACTIVITY_VISIBLE else ACTION_ACTIVITY_HIDDEN - context.startService(Intent(context, SessionService::class.java).setAction(action).putExtra(EXTRA_DISPLAY_ID, displayId)) + SessionState.activityDisplayId = displayId + context.startService(Intent(context, SessionService::class.java).setAction(action) + .putExtra(EXTRA_DISPLAY_ID, displayId) + .putExtra(EXTRA_ACTIVITY_DISPLAY_ID, displayId)) } fun setActivityDisplay(context: Context, displayId: Int) { if (!SessionState.running) return - context.startService(Intent(context, SessionService::class.java).setAction(ACTION_ACTIVITY_DISPLAY).putExtra(EXTRA_DISPLAY_ID, displayId)) + SessionState.activityDisplayId = displayId + context.startService(Intent(context, SessionService::class.java).setAction(ACTION_ACTIVITY_DISPLAY) + .putExtra(EXTRA_DISPLAY_ID, displayId)) + context.startService(Intent(context, SessionService::class.java).setAction(ACTION_ACTIVITY_DISPLAY_CHANGED) + .putExtra(EXTRA_ACTIVITY_DISPLAY_ID, displayId)) + } + + @Suppress("DEPRECATION") + private fun contextDisplayId(context: Context): Int { + val activity = context as? android.app.Activity ?: return Display.DEFAULT_DISPLAY + return if (Build.VERSION.SDK_INT >= 30) activity.display?.displayId ?: activity.windowManager.defaultDisplay.displayId + else activity.windowManager.defaultDisplay.displayId } fun setXrActivityVisible(context: Context, visible: Boolean) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt index ab32b90591..cebc33caa0 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -42,6 +42,8 @@ object SessionState { @Volatile var running = false @Volatile + var activityDisplayId = 0 + @Volatile var runtimeDriver: String? = null var suspended by mutableStateOf(false) @Volatile var pipActive = false diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionVisibilityPolicy.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionVisibilityPolicy.kt new file mode 100644 index 0000000000..90630ebbcd --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionVisibilityPolicy.kt @@ -0,0 +1,15 @@ +package com.droiddeck.launcher.session + +internal object SessionVisibilityPolicy { + fun isHidden( + activityStarted: Boolean, + defaultDisplayOn: Boolean, + activityOnDefaultDisplay: Boolean, + activityDisplayOn: Boolean, + xrActivityVisible: Boolean = false, + ): Boolean = !sessionHasVisibleSurface( + panelVisible = activityStarted, + screenOn = if (activityOnDefaultDisplay) defaultDisplayOn else activityDisplayOn, + xrVisible = xrActivityVisible, + ) +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index 3d1ee8183d..03193510cc 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -15,7 +15,8 @@ object SettingsReset { "gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature", "storesInstallLanguage", "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "touch", "osc", "shape", "steamController", - "gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "stretch16x9", "picturePosition", + "gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController", + "stretch16x9", "picturePosition", "gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop", "tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus", diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt index bee26dd0dc..5e63d7b0f2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt @@ -23,6 +23,8 @@ import androidx.compose.foundation.LocalIndication import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.hoverable import androidx.compose.foundation.interaction.MutableInteractionSource @@ -493,7 +495,7 @@ private fun IconSuggestions(repo: String, selected: String?, onPick: (String) -> if (list != null && list.isEmpty()) return Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.height(44.dp)) { Small(stringResource(if (list == null) R.string.add_app_icon_searching else R.string.add_app_icon_suggestions)) - if (list != null) Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) { + if (list != null) Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState()).selectableGroup()) { list.forEachIndexed { i, url -> Rise(i) { SuggestedIcon(url, url == selected) { onPick(url) } } } } } @@ -510,7 +512,7 @@ private fun SuggestedIcon(url: String, selected: Boolean, onClick: () -> Unit) { contentAlignment = Alignment.Center, modifier = Modifier.size(44.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(colors.surface) .glideBorder(hot, Shape12, pal.signal, pal.line2) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick) + .hoverable(src).selectable(selected = selected, role = androidx.compose.ui.semantics.Role.RadioButton, interactionSource = src, indication = LocalIndication.current, onClick = onClick) .controllerConfirm(onClick = onClick), ) { AsyncImage(model = ImageRequest.Builder(LocalContext.current).data(url).crossfade(true).build(), contentDescription = stringResource(R.string.add_app_icon), contentScale = ContentScale.Fit, modifier = Modifier.size(34.dp)) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ColorPickerDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ColorPickerDialog.kt new file mode 100644 index 0000000000..e94f193e95 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ColorPickerDialog.kt @@ -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) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt index e3de1f325e..0e99b6e714 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt @@ -1323,7 +1323,7 @@ internal fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = fa modifier = Modifier.size(44.dp).clip(RoundedCornerShape(12.dp)) .background(if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent) .glideBorder(hot, RoundedCornerShape(12.dp), pal.signal, pal.line2) - .hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick), ) { if (busy) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp)) @@ -1342,7 +1342,7 @@ private fun SmallButton(text: String, enabled: Boolean = true, accent: Boolean = modifier = modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(10.dp)) .background(if (hot) pal.signal else colors.surfaceVariant) .glideBorder(hot, RoundedCornerShape(10.dp), colors.onBackground, pal.line2, restWidth = 2.dp) - .hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = 14.dp, vertical = 8.dp), ) { @@ -1422,7 +1422,7 @@ private fun ChoiceLine( modifier = Modifier.padding(end = 6.dp).size(44.dp).clip(ROW_SHAPE) .background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent) .glideBorder(delHot, ROW_SHAPE, colors.error) - .hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete) + .hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, onClick = onDelete) .controllerConfirm(onClick = onDelete), ) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt index bfdde089a6..2a22c0a155 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt @@ -15,6 +15,7 @@ import androidx.compose.ui.focus.focusProperties import androidx.compose.ui.focus.focusRequester import androidx.compose.foundation.border import androidx.compose.foundation.clickable +import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -105,7 +106,7 @@ fun DriverPage( .glideBorder(refreshHot, RoundedCornerShape(10.dp), pal.signal, pal.line) .focusRequester(refreshFocus) .hoverable(refreshSrc) - .clickable(interactionSource = refreshSrc, indication = null, enabled = !checking, onClick = onRefresh), + .clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = refreshSrc, indication = null, enabled = !checking, onClick = onRefresh), ) { if (checking) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp)) else Icon(Icons.Outlined.Refresh, contentDescription = stringResource(R.string.comp_check_drivers), tint = colors.onBackground, modifier = Modifier.size(20.dp)) @@ -185,7 +186,7 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).then(modifier).focusRequester(mainFocus) .then(if (row.removable) Modifier.focusProperties { right = delFocus } else Modifier) - .hoverable(src).clickable(interactionSource = src, indication = null, onClick = onSelect) + .hoverable(src).selectable(selected = selected, role = androidx.compose.ui.semantics.Role.RadioButton, interactionSource = src, indication = null, onClick = onSelect) .padding(horizontal = 11.dp, vertical = 8.dp), ) { Box( @@ -218,7 +219,7 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit .glideBorder(delHot, RoundedCornerShape(10.dp), colors.error) .focusRequester(delFocus) .focusProperties { left = mainFocus } - .hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete), + .hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, onClick = onDelete), ) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, row.name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) } } } @@ -235,7 +236,7 @@ internal fun FocusText(text: String, color: Color, modifier: Modifier = Modifier modifier = modifier.clip(shape) .background(if (hot) color.copy(alpha = 0.14f) else Color.Transparent) .glideBorder(hot, shape, color) - .hoverable(src).clickable(interactionSource = src, indication = null, onClick = onClick) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, onClick = onClick) .padding(horizontal = 12.dp, vertical = 8.dp), ) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndArt.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndArt.kt index 85386ca935..eef6fd19ca 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndArt.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndArt.kt @@ -131,7 +131,7 @@ private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableIntera .background(colors.surface) .glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp) .alpha(if (t.dim && !hot) 0.55f else 1f) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = t.onClick), + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = t.onClick), ) { Box(modifier = Modifier.fillMaxWidth().shine(hot)) { Art(t.art, t.iconRes, t.title, Modifier.fillMaxWidth(), wide, t.iconBitmap) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt index f86062e241..dcb5eece6d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt @@ -559,7 +559,7 @@ private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Uni .clip(Shape12) .background(if (selected) pal.signal.copy(alpha = 0.14f) else if (hovered) Color.White.copy(alpha = 0.05f) else Color.Transparent) .glideBorder(focused, Shape12, pal.signal) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onSelect) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onSelect) .controllerConfirm(onClick = onLaunch) .padding(horizontal = 10.dp, vertical = 6.dp), ) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index c5a0c6866e..7136ac7f07 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt @@ -22,6 +22,8 @@ import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.hoverable +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsFocusedAsState import androidx.compose.foundation.interaction.collectIsHoveredAsState @@ -119,7 +121,7 @@ internal fun SideRail( Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp), - modifier = Modifier.fillMaxWidth(), + modifier = Modifier.fillMaxWidth().selectableGroup(), ) { val place: (String) -> Modifier = { key -> Modifier.onGloballyPositioned { @@ -192,7 +194,7 @@ private fun RailItem( .background(fill) .glideBorder(focused, Shape14, pal.signal) .hoverable(src) - .clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick) + .selectable(selected = current, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick) .then(if (iconOnly) Modifier.semantics { contentDescription = label } else Modifier), ) { if (iconOnly) Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(22.dp)) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index 0fe6652f5e..bd4b350cdc 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -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 -> @@ -796,3 +797,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) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt index d59e87ce8f..fb7d204852 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt @@ -187,7 +187,7 @@ internal fun PrimaryButton( .background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant))) .then(if (enabled) Modifier else Modifier.border(1.dp, pal.line2, Shape12)) .then(if (hot) Modifier.border(2.dp, pal.signal, Shape12) else Modifier) - .hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled) { + .hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = null, enabled = enabled) { placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) } onClick() } @@ -250,7 +250,7 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boo contentAlignment = Alignment.Center, modifier = modifier.paneItem("btn:$text").downToFirstTile().heightIn(min = if (compact) 44.dp else 48.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).glideBorder(hot, Shape12, pal.signal, pal.line2) .alpha(if (enabled) 1f else 0.5f) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = if (compact) 10.dp else 16.dp, vertical = if (compact) 7.dp else 11.dp), ) { @@ -272,7 +272,7 @@ internal fun Cog(size: androidx.compose.ui.unit.Dp = 48.dp, onClick: () -> Unit) Box( contentAlignment = Alignment.Center, modifier = Modifier.paneItem("cog").downToFirstTile().size(size).onGloballyPositioned { placed[0] = it }.clip(if (size > 48.dp) Shape14 else Shape12).background(Color.White.copy(alpha = 0.03f)).glideBorder(hot, if (size > 48.dp) Shape14 else Shape12, pal.signal, pal.line2) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current) { + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current) { placed[0]?.takeIf { it.isAttached }?.let { PageOrigin.mark(Origin(it.boundsInRoot(), cornerPx)) } spins++ onClick() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt index 50ce39b29a..92e0aef3bc 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt @@ -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) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt index 01240610dd..c428b8b97d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt @@ -18,6 +18,8 @@ import androidx.compose.foundation.focusGroup import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.detectVerticalDragGestures import androidx.compose.foundation.hoverable +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsHoveredAsState import androidx.compose.foundation.layout.Arrangement @@ -715,7 +717,7 @@ internal fun SheetChips( horizontalArrangement = Arrangement.spacedBy(ChipGap), modifier = (if (equal) Modifier.fillMaxWidth() else Modifier) .focusProperties { enter = { chips.getOrNull(selected) ?: FocusRequester.Default } } - .focusGroup(), + .focusGroup().selectableGroup(), ) { labels.forEachIndexed { i, label -> val m = (if (equal) Modifier.weight(1f) else Modifier.widthIn(min = least)) @@ -743,7 +745,7 @@ private fun SheetChip(label: String, on: Boolean, modifier: Modifier, onClick: ( .background(if (under) Color.Transparent else colors.surfaceVariant.copy(alpha = 0.5f)) .shownBar(on, pal.signal) .glideBorder(hot, shape, pal.signal, if (under) Color.Transparent else pal.line) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick) + .hoverable(src).selectable(selected = on, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick) .controllerConfirm(onClick = onClick) .padding(horizontal = 14.dp, vertical = 8.dp), ) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index cb7ec92516..778673e92d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -88,6 +88,7 @@ class ModeSettings( val mangoapp: Boolean = true, val steamController: String? = null, val unfoldedControls: Boolean? = null, + val unfoldedControlsWithController: Boolean = false, val runSteamAtStartup: Boolean = false, val bootMovie: String? = null, val bootMovieSound: Boolean = true, @@ -140,6 +141,7 @@ class ModeSettingsActions( val onReturnAfterGame: (Boolean) -> Unit = {}, val onSteamController: (String) -> Unit = {}, val onUnfoldedControls: (Boolean) -> Unit = {}, + val onUnfoldedControlsWithController: (Boolean) -> Unit = {}, val onRunSteamAtStartup: (Boolean) -> Unit = {}, val onBootMovie: (String) -> Unit = {}, val onBootMovieSound: (Boolean) -> Unit = {}, @@ -290,6 +292,11 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: stringResource(R.string.unfolded_controls_hint), s.unfoldedControls, onChange = a.onUnfoldedControls, ) + if (steam && s.unfoldedControls == true) ToggleRow( + host, "unfolded-controls-with-controller", stringResource(R.string.unfolded_controls_with_controller), + stringResource(R.string.unfolded_controls_with_controller_hint), + s.unfoldedControlsWithController, onChange = a.onUnfoldedControlsWithController, + ) if (steam) ChoiceRow( host, "back-actions", stringResource(R.string.mode_back), stringResource(SessionPrefs.backActionsOrder(s.backActionsInverted)), listOf( diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt b/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt index 0567319f30..0fc5762777 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt @@ -234,7 +234,7 @@ private fun HeaderButton(text: String, onClick: () -> Unit) { modifier = Modifier.fillMaxHeight() .background(Color.White.copy(alpha = 0.08f), RoundedCornerShape(7.dp)) .glideBorder(focused, RoundedCornerShape(7.dp), pal.signal, Color.White.copy(alpha = 0.14f)) - .clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick) + .clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onClick) .padding(horizontal = 12.dp), ) { Text(text, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = Color.White) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 962cdef820..58b4c11eea 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -278,6 +278,8 @@ class DrawerActions( val onPipAutoEnter: (Boolean) -> Unit = {}, val unfoldedControls: Boolean? = null, val onUnfoldedControls: (Boolean) -> Unit = {}, + val unfoldedControlsWithController: Boolean = false, + val onUnfoldedControlsWithController: (Boolean) -> Unit = {}, val onShareLogs: () -> Unit, val onStop: () -> Unit, val onStopFrom: ((androidx.compose.ui.geometry.Rect?) -> Unit)? = null, @@ -575,6 +577,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls), stringResource(R.string.unfolded_controls_hint), a.unfoldedControls, chipModifier = focus.track(page, "unfolded-controls"), onChange = a.onUnfoldedControls) + if (a.steam && a.unfoldedControls == true) ToggleRow(host, "unfolded-controls-with-controller", + stringResource(R.string.unfolded_controls_with_controller), + stringResource(R.string.unfolded_controls_with_controller_hint), a.unfoldedControlsWithController, + chipModifier = focus.track(page, "unfolded-controls-with-controller"), + onChange = a.onUnfoldedControlsWithController) } SettingsGroup(stringResource(R.string.drawer_latency)) { ToggleRow(host, "low-latency-controller", stringResource(R.string.drawer_low_latency_controller), @@ -754,7 +761,7 @@ private fun DrawerActionButton(text: String, icon: androidx.compose.ui.graphics. modifier = modifier.fillMaxWidth().heightIn(min = 52.dp).clip(shape) .background(if (hot) pal.signal.copy(alpha = 0.16f) else colors.surfaceVariant) .glideBorder(hot, shape, pal.signal) - .hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, onClick = onClick) + .hoverable(source).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = source, indication = LocalIndication.current, onClick = onClick) .controllerConfirm(onClick = onClick).padding(horizontal = 16.dp, vertical = 10.dp), ) { Icon(icon, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(22.dp)) @@ -791,7 +798,7 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = modifier.heightIn(min = 44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop") .clip(shape).background(fill).glideBorder(hot, shape, colors.error.copy(alpha = 0.9f), colors.error.copy(alpha = 0.55f)) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onClick) .controllerConfirm(onClick = onClick) .padding(start = 12.dp, end = 14.dp), ) { @@ -817,7 +824,7 @@ private fun SteamActionPill( .clip(shape).background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent) .glideBorder(hot, shape, pal.signal, pal.line) .hoverable(interactionSource) - .clickable(interactionSource = interactionSource, indication = LocalIndication.current, onClick = onClick) + .clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = interactionSource, indication = LocalIndication.current, onClick = onClick) .controllerConfirm(onClick = onConfirm ?: onClick), ) { Icon(icon, contentDescription = null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(20.dp)) @@ -836,7 +843,7 @@ private fun DrawerBumper(label: String, description: String, modifier: Modifier contentAlignment = Alignment.Center, modifier = modifier.size(44.dp).clip(ring) .glideBorder(hot, ring, pal.signal) - .hoverable(src).clickable(interactionSource = src, indication = null, onClick = onClick) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, onClick = onClick) .controllerConfirm(onClick = onClick) .semantics { contentDescription = description }, ) { @@ -857,7 +864,7 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List(340, easing = FastOutSlowInEasing) androidx.compose.foundation.layout.BoxWithConstraints( contentAlignment = Alignment.Center, - modifier = modifier.height(if (compact) 44.dp else 64.dp).clipToBounds(), + modifier = modifier.height(if (compact) 44.dp else 64.dp).clipToBounds().selectableGroup(), ) { val tab = if (compact) 36f else 44f val spacing = ((maxWidth.value - tab) / ((count - 1) * (1f + DRAWER_TAB_LEAN_DP / DRAWER_TAB_SPACING_DP))).coerceIn(24f, DRAWER_TAB_SPACING_DP) @@ -890,7 +897,7 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List val on = i == selected @@ -197,7 +199,7 @@ internal fun TabStrip( .clip(tabShape) .background(if (on) pal.signal else if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent) .glideBorder(hot, tabShape, if (on) colors.onBackground else pal.signal) - .hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Tab, onClick = pick) + .hoverable(src).selectable(selected = on, interactionSource = src, indication = null, role = Role.Tab, onClick = pick) .controllerConfirm(onClick = pick) .padding(horizontal = tabPadding, vertical = if (compact) 6.dp else 12.dp), ) @@ -367,7 +369,7 @@ fun MenuItem( .clip(RoundedCornerShape(8.dp)) .background(if (hot && enabled) Color.White.copy(alpha = 0.07f) else Color.Transparent) .alpha(if (enabled) 1f else 0.4f) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = 10.dp, vertical = 9.dp), ) { @@ -400,7 +402,7 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo .background(colors.surfaceVariant) .glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, if (open) pal.signal else pal.line2) .alpha(if (enabled) 1f else 0.5f) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = 12.dp, vertical = 8.dp), ) { @@ -791,7 +793,7 @@ fun SegmentedTabs(options: List>, selected: T?, modifier: Mo .graphicsLayer { alpha = shown } .clip(pillShape).background(pal.signal), ) - Row { + Row(Modifier.selectableGroup()) { options.forEachIndexed { i, (value, label) -> val src = remember { MutableInteractionSource() } val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value @@ -810,9 +812,8 @@ fun SegmentedTabs(options: List>, selected: T?, modifier: Mo modifier = tabModifier(value).width(segment).fillMaxHeight() .clip(pillShape) .glideBorder(hot, pillShape, if (chosen) pal.onSignal else pal.signal) - .semantics { role = Role.Tab; this.selected = chosen } .hoverable(src) - .clickable(interactionSource = src, indication = LocalIndication.current, onClick = pick) + .selectable(selected = chosen, role = Role.Tab, interactionSource = src, indication = LocalIndication.current, onClick = pick) .controllerConfirm(onClick = pick), ) { Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = ink, maxLines = 1, softWrap = false) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt index 4f71f68b38..1492362f12 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt @@ -370,7 +370,7 @@ internal fun DrawerAchievementsRow(progress: Pair?, modifier: Modifier modifier = modifier.fillMaxWidth().height(44.dp).clip(shape) .background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface) .glideBorder(hot, shape, pal.signal, pal.line) - .clickable(interactionSource = interaction, indication = LocalIndication.current, onClick = onClick) + .clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = interaction, indication = LocalIndication.current, onClick = onClick) .controllerConfirm(onClick = onClick) .padding(horizontal = 12.dp), ) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index 182f3a1d52..175cbecd85 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -60,6 +60,8 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.focusGroup import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.hoverable +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Arrangement @@ -1150,7 +1152,7 @@ private fun HeaderTabs(labels: List, selected: Int, onSelect: (Int) -> U val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val shape = RoundedCornerShape(8.dp) - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.selectableGroup()) { labels.forEachIndexed { i, label -> val src = remember { MutableInteractionSource() } val hot = rememberHot(src) @@ -1159,7 +1161,7 @@ private fun HeaderTabs(labels: List, selected: Int, onSelect: (Int) -> U label, fontSize = 15.sp, fontWeight = FontWeight.Bold, maxLines = 1, color = if (i == selected || hot) colors.onBackground else colors.onSurfaceVariant.copy(alpha = 0.7f), modifier = Modifier.clip(shape).glideBorder(hot, shape, pal.signal) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = pick) + .hoverable(src).selectable(selected = i == selected, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = pick) .controllerConfirm(onClick = pick) .padding(horizontal = 4.dp, vertical = 6.dp), ) @@ -1363,7 +1365,7 @@ private fun GameListRow( modifier = Modifier.fillMaxWidth().heightIn(min = 64.dp).then(navigation).paneItem("card:${item.key}") .then(if (first) Modifier.firstTile() else Modifier) .clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open) .padding(horizontal = 10.dp, vertical = 8.dp), ) { CardArt(item, Modifier.width(96.dp).height(54.dp).clip(RoundedCornerShape(8.dp))) @@ -1481,7 +1483,7 @@ private fun GameCard( } .then(navigation).paneItem("card:${item.key}").then(if (first) Modifier.firstTile() else Modifier).graphicsLayer { scaleX = scale; scaleY = scale } .clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open), + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open), ) { CardFace(item, download, hot, capsule) { CardMarker(item, installed, download, compact = capsule) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt b/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt index e33ebde335..0f3843fcac 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt @@ -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 = 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) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ThemeColors.kt b/app/src/main/java/com/droiddeck/launcher/ui/ThemeColors.kt new file mode 100644 index 0000000000..b4b57737e1 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ThemeColors.kt @@ -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), + ) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/TrackingRecoveryView.kt b/app/src/main/java/com/droiddeck/launcher/ui/TrackingRecoveryView.kt index 44c53a670c..3a122445cb 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/TrackingRecoveryView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/TrackingRecoveryView.kt @@ -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() @@ -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 diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 8002743d4f..d60a59fb94 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1460,6 +1460,14 @@ خلفية سوداء ونص أبيض، والأزرق لكل عنصر محدَّد أو مُركَّز عليه أو مضغوط. كحلي كهربائي أزرق أكثر سطوعًا، على أسطح تميل إلى الكحلي بدلاً من الرمادي. + تدرج لوني + لونك الأساسي والثانوي، ممزوجان على الأزرار وعناصر التمييز. + الأساسي + الثانوي + درجة اللون + التشبع + السطوع + لون سداسي (Hex) Esc Ins Del @@ -2599,6 +2607,7 @@ في انتظار اتصال USB Ethernet الخاص بالنظارة. قد لا يتيحه هذا الهاتف للتطبيقات. انقطع اتصال XREAL أو أعاد استجابة غير مدعومة. جارٍ إعادة المحاولة… دعم تجريبي لـ 1S. استخدم وضع Follow وعطّل تثبيت الصورة من قائمة النظارة. لا تزال اتجاهات التتبّع وأوضاع العرض بحاجة إلى اختبار على الجهاز. + تتبّع تجريبي لحركة الرأس لنظارة Pro 2. لا يُدعم بعد ضبط السطوع ومستوى الصوت أو تبديل وضع العرض. Cardboard VR وضع Cardboard عرض للعين اليسرى وآخر لليمنى لنظارة واقع افتراضي للهاتف. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index fb9b4c3c93..b924266f43 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1029,6 +1029,7 @@ Esperando la conexión Ethernet por USB de las gafas. Puede que este teléfono no la ofrezca a las apps. La conexión con las XREAL se interrumpió o devolvió una respuesta no compatible. Reintentando… Compatibilidad experimental con las 1S. Usa el modo Follow y desactiva la estabilización en el menú de las gafas. Aún falta probar en el dispositivo las direcciones del seguimiento y los modos de pantalla. + Seguimiento de cabeza experimental para Pro 2. Los ajustes de brillo y volumen y el cambio de modo de pantalla aún no son compatibles. En lugar de View/Select. Animaciones Los sticks aparecen donde tocas y se ocultan al soltar @@ -1468,6 +1469,14 @@ Fondo negro, texto blanco y el azul para todo lo seleccionado, enfocado o presionado. Azul marino eléctrico Un azul más vivo, sobre superficies que tiran a azul marino en vez de gris. + Degradado + Tus propios colores primario y secundario, combinados en botones y resaltados. + Primario + Secundario + Tono + Saturación + Brillo + Color hexadecimal Esc Insert Supr diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 52c09a0152..f6d820e9e4 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -1404,6 +1404,14 @@ Черен фон, бял текст, синьото за всичко избрано, на фокус или натиснато. Яркосиньо По-яркото синьо, върху повърхности, по-близки до тъмносиньо, вместо сиво. + Градиент + Вашите основен и вторичен цвят, смесени в бутоните и акцентите. + Основен + Вторичен + Нюанс + Наситеност + Яркост + Hex цвят Esc Ins Del @@ -2499,6 +2507,7 @@ Изчаква се USB Ethernet връзката на очилата. Този телефон може да не я предоставя на приложенията. Връзката с XREAL беше прекъсната или върна неподдържан отговор. Нов опит… Експериментална поддръжка на 1S. Използвайте режим Follow и изключете стабилизацията в менюто на очилата. Посоките на проследяване и режимите на показване все още трябва да се тестват на устройство. + Експериментално проследяване на движенията на главата за Pro 2. Регулирането на яркостта и силата на звука и превключването на режима на показване все още не се поддържат. Cardboard VR Режим Cardboard Изображения за лявото и дясното око за VR очила за телефон. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 9df47991c7..74c7e327f9 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1432,6 +1432,14 @@ Černé pozadí, bílé písmo, modrá pro vše vybrané, zaměřené nebo stisknuté. Elektrická modř Jasnější modrá na povrchách, které jsou spíše tmavomodré než šedé. + Přechod + Vaše vlastní primární a sekundární barva, prolnuté na tlačítkách a zvýrazněních. + Primární + Sekundární + Odstín + Sytost + Jas + Barva hex Esc Ins Del @@ -2549,6 +2557,7 @@ Čeká se na připojení USB Ethernet brýlí. Tento telefon ho možná aplikacím nezpřístupňuje. Připojení XREAL bylo přerušeno nebo vrátilo nepodporovanou odpověď. Zkouší se to znovu… Experimentální podpora 1S. V nabídce brýlí použijte režim Follow a vypněte stabilizaci. Směry sledování a režimy zobrazení je ještě třeba otestovat na zařízení. + Experimentální sledování pohybu hlavy pro Pro 2. Nastavení jasu, hlasitosti a přepínání režimů zobrazení zatím nejsou podporovány. Cardboard VR Režim Cardboard Obraz pro levé a pravé oko pro VR brýle pro telefon. diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 6b200711de..062bcb4b54 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -1404,6 +1404,14 @@ Sort baggrund, hvid skrift, blå til alt, der er valgt, fokuseret eller trykket. Elektrisk marineblå Den blå er klarere, på overflader der trækker mod marineblåt i stedet for gråt. + Gradient + Dine egne primære og sekundære farver, blandet på knapper og fremhævninger. + Primær + Sekundær + Farvetone + Mætning + Lysstyrke + Hex-farve Esc Ins Del @@ -2499,6 +2507,7 @@ Venter på brillens USB-Ethernet-forbindelse. Denne telefon gør den muligvis ikke tilgængelig for apps. XREAL-forbindelsen blev afbrudt eller returnerede et svar, der ikke understøttes. Prøver igen… Eksperimentel understøttelse af 1S. Brug Follow-tilstand, og slå stabilisering fra i brillens menu. Sporingsretninger og visningstilstande mangler stadig test på enheden. + Eksperimentel hovedsporing til Pro 2. Justering af lysstyrke og lydstyrke samt skift af visningstilstand understøttes endnu ikke. Cardboard VR Cardboard-tilstand Billeder til venstre og højre øje til en VR-brille til telefonen. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index d284aa1275..d46e0c5758 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1393,6 +1393,14 @@ Schwarzer Grund, weiße Schrift, das Blau für alles Ausgewählte, Fokussierte oder Gedrückte. Elektrisches Marineblau Das Blau heller, auf Flächen, die eher zu Marineblau als zu Grau tendieren. + Farbverlauf + Eigene Primär- und Sekundärfarbe, als Verlauf auf Schaltflächen und Hervorhebungen. + Primär + Sekundär + Farbton + Sättigung + Helligkeit + Hex-Farbe Esc Einfg Entf @@ -2485,6 +2493,7 @@ Warte auf die USB-Ethernet-Verbindung der Brille. Dieses Smartphone stellt sie Apps möglicherweise nicht bereit. Die XREAL-Verbindung wurde unterbrochen oder hat eine nicht unterstützte Antwort geliefert. Neuer Versuch … Experimentelle Unterstützung für die 1S. Nutze den Follow-Modus und deaktiviere die Stabilisierung im Menü der Brille. Tracking-Richtungen und Anzeigemodi müssen noch auf Geräten getestet werden. + Experimentelles Kopftracking für Pro 2. Das Einstellen von Helligkeit und Lautstärke sowie das Umschalten des Anzeigemodus werden noch nicht unterstützt. Cardboard VR Cardboard-Modus Bilder für linkes und rechtes Auge für eine Smartphone-VR-Brille. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 409cda9ecf..dd6458776e 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1404,6 +1404,14 @@ Μαύρο φόντο, λευκά γράμματα, το μπλε για ό,τι είναι επιλεγμένο, εστιασμένο ή πατημένο. Ηλεκτρικό ναυτικό μπλε Το μπλε πιο έντονο, σε επιφάνειες που τείνουν προς το ναυτικό μπλε αντί για γκρι. + Διαβάθμιση + Δικά σας πρωτεύον και δευτερεύον χρώμα, σε μίξη στα κουμπιά και τις επισημάνσεις. + Πρωτεύον + Δευτερεύον + Απόχρωση + Κορεσμός + Φωτεινότητα + Χρώμα hex Esc Ins Del @@ -2499,6 +2507,7 @@ Αναμονή για τη σύνδεση USB Ethernet των γυαλιών. Αυτό το τηλέφωνο ίσως δεν τη διαθέτει στις εφαρμογές. Η σύνδεση XREAL διακόπηκε ή επέστρεψε μη υποστηριζόμενη απόκριση. Νέα προσπάθεια… Πειραματική υποστήριξη για 1S. Χρησιμοποιήστε τη λειτουργία Follow και απενεργοποιήστε τη σταθεροποίηση στο μενού των γυαλιών. Οι κατευθύνσεις παρακολούθησης και οι λειτουργίες οθόνης χρειάζονται ακόμα δοκιμή σε συσκευή. + Πειραματική παρακολούθηση κεφαλής για Pro 2. Η ρύθμιση της φωτεινότητας και της έντασης ήχου και η αλλαγή λειτουργίας οθόνης δεν υποστηρίζονται ακόμη. Cardboard VR Λειτουργία Cardboard Εικόνες για το αριστερό και το δεξί μάτι, για γυαλιά VR κινητού. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 85e1bf0a4b..9060bac1e7 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1417,6 +1417,14 @@ Fondo negro, texto blanco y el azul para todo lo seleccionado, enfocado o pulsado. Azul marino eléctrico Un azul más vivo, sobre superficies que tiran a azul marino en vez de gris. + Degradado + Tus propios colores primario y secundario, combinados en botones y resaltados. + Primario + Secundario + Tono + Saturación + Brillo + Color hexadecimal Esc Insert Supr @@ -2509,6 +2517,7 @@ Esperando la conexión Ethernet por USB de las gafas. Puede que este teléfono no la ofrezca a las apps. La conexión con las XREAL se interrumpió o devolvió una respuesta no compatible. Reintentando… Compatibilidad experimental con las 1S. Usa el modo Follow y desactiva la estabilización en el menú de las gafas. Aún falta probar en el dispositivo las direcciones del seguimiento y los modos de pantalla. + Seguimiento de cabeza experimental para Pro 2. Los ajustes de brillo y volumen y el cambio de modo de pantalla aún no son compatibles. Desarrollador Distribuidor Lanzamiento diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index b6757f5e74..a6e7493725 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -1404,6 +1404,14 @@ Musta pohja, valkoinen teksti, sininen kaikessa valitussa, kohdistetussa tai painetussa. Sähköinen laivastonsininen Sininen kirkkaampana pinnoilla, jotka taittuvat harmaan sijaan laivastonsiniseen. + Liukuväri + Omat ensisijainen ja toissijainen värisi, sulautettuina painikkeisiin ja korostuksiin. + Ensisijainen + Toissijainen + Sävy + Kylläisyys + Kirkkaus + Hex-väri Esc Ins Del @@ -2499,6 +2507,7 @@ Odotetaan lasien USB-Ethernet-yhteyttä. Tämä puhelin ei ehkä tarjoa sitä sovelluksille. XREAL-yhteys katkesi tai palautti vastauksen, jota ei tueta. Yritetään uudelleen… Kokeellinen 1S-tuki. Käytä Follow-tilaa ja poista vakautus käytöstä lasien valikosta. Seurannan suunnat ja näyttötilat vaativat vielä testausta laitteella. + Kokeellinen päänliikkeiden seuranta Pro 2:lle. Kirkkauden ja äänenvoimakkuuden säätöä sekä näyttötilan vaihtamista ei vielä tueta. Cardboard VR Cardboard-tila Vasemman ja oikean silmän kuvat puhelimen VR-laseille. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index af743337c4..9e7d00dcc7 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1417,6 +1417,14 @@ Fond noir, texte blanc, et le bleu pour tout élément sélectionné, ciblé ou pressé. Marine électrique Un bleu plus vif, sur des surfaces qui tirent vers le marine plutôt que vers le gris. + Dégradé + Vos propres couleurs primaire et secondaire, fondues sur les boutons et les éléments en surbrillance. + Primaire + Secondaire + Teinte + Saturation + Luminosité + Couleur hex Échap Inser Suppr @@ -2520,6 +2528,7 @@ En attente de la connexion Ethernet USB des lunettes. Ce téléphone ne la rend peut-être pas accessible aux applications. La connexion XREAL a été interrompue ou a renvoyé une réponse non prise en charge. Nouvelle tentative… Prise en charge expérimentale des 1S. Utilisez le mode Follow et désactivez la stabilisation dans le menu des lunettes. Le sens du suivi et les modes d\'affichage restent à tester sur l\'appareil. + Suivi expérimental des mouvements de la tête pour Pro 2. Le réglage de la luminosité et du volume ainsi que le changement de mode d\'affichage ne sont pas encore pris en charge. Développeur Éditeur Sortie diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 38eac11933..c7d0f6005e 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -1404,6 +1404,14 @@ काली ज़मीन, सफ़ेद टाइप, चुने, फ़ोकस या दबाए गए हर चीज़ के लिए ब्लू रंग। इलेक्ट्रिक नेवी ब्लू रंग ज़्यादा चमकीला, उन सतहों पर जो ग्रे के बजाय नेवी की ओर झुकती हैं। + ग्रेडिएंट + आपके अपने प्राथमिक और द्वितीयक रंग, बटनों और हाइलाइट पर मिश्रित। + प्राथमिक + द्वितीयक + रंगत + संतृप्ति + चमक + हेक्स रंग Esc Ins Del @@ -2499,6 +2507,7 @@ चश्मे के USB Ethernet कनेक्शन का इंतज़ार है। हो सकता है यह फ़ोन इसे ऐप्स को उपलब्ध न कराए। XREAL कनेक्शन टूट गया या उसने ऐसा जवाब दिया जो समर्थित नहीं है। फिर से कोशिश हो रही है… 1S के लिए प्रायोगिक सपोर्ट। चश्मे के मेनू में Follow मोड चुनें और स्टेबिलाइज़ेशन बंद करें। ट्रैकिंग की दिशाएं और डिस्प्ले मोड अभी डिवाइस पर टेस्ट होने बाकी हैं। + Pro 2 के लिए प्रायोगिक हेड ट्रैकिंग। चमक और वॉल्यूम बदलना और डिस्प्ले मोड स्विच करना अभी समर्थित नहीं है। Cardboard VR Cardboard मोड फ़ोन VR व्यूअर के लिए बाईं और दाईं आंख के व्यू। diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index a307b5aedd..c146857a5e 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -1404,6 +1404,14 @@ Fekete alap, fehér betűk, a kék minden kijelölt, fókuszált vagy lenyomott elemhez. Elektromos tengerészkék Fényesebb kék, szürke helyett tengerészkék felületeken. + Színátmenet + Saját elsődleges és másodlagos színed, átmenettel a gombokon és a kiemeléseken. + Elsődleges + Másodlagos + Színárnyalat + Telítettség + Fényerő + Hex szín Esc Ins Del @@ -2499,6 +2507,7 @@ Várakozás a szemüveg USB-s Ethernet-kapcsolatára. Lehet, hogy ez a telefon nem teszi elérhetővé az alkalmazások számára. Az XREAL-kapcsolat megszakadt, vagy nem támogatott választ adott. Újrapróbálkozás… Kísérleti 1S-támogatás. Használja a Follow módot, és kapcsolja ki a stabilizálást a szemüveg menüjében. A követési irányokat és a megjelenítési módokat még tesztelni kell az eszközön. + Kísérleti fejkövetés a Pro 2-höz. A fényerő és a hangerő beállítása, valamint a megjelenítési mód váltása még nem támogatott. Cardboard VR Cardboard mód Bal és jobb szem képe telefonos VR-szemüveghez. diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index f1cbe95432..8208d2fa3c 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -1390,6 +1390,14 @@ Dasar hitam, tipe putih, biru untuk semua yang dipilih, difokuskan, atau ditekan. Navy elektrik Biru yang lebih cerah, pada permukaan yang condong ke navy, bukan abu-abu. + Gradasi + Warna primer dan sekunder pilihan Anda, dipadukan pada tombol dan sorotan. + Primer + Sekunder + Rona + Saturasi + Kecerahan + Warna hex Esc Ins Del @@ -2474,6 +2482,7 @@ Menunggu koneksi Ethernet USB dari kacamata. Ponsel ini mungkin tidak menyediakannya untuk aplikasi. Koneksi XREAL terputus atau memberikan respons yang tidak didukung. Mencoba lagi… Dukungan 1S eksperimental. Gunakan mode Follow dan nonaktifkan stabilisasi di menu kacamata. Arah pelacakan dan mode tampilan masih perlu diuji di perangkat. + Pelacakan kepala Pro 2 eksperimental. Pengaturan kecerahan, volume, dan pergantian mode tampilan belum didukung. Cardboard VR Mode Cardboard Tampilan mata kiri dan kanan untuk kacamata VR ponsel. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 9493ae1b15..75e4645136 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1407,6 +1407,14 @@ Fondo nero, testo bianco, il blu per tutto ciò che è selezionato, attivo o premuto. Blu elettrico Il blu più brillante, su superfici che tendono al blu navy invece che al grigio. + Gradiente + I tuoi colori primario e secondario, sfumati su pulsanti ed evidenziazioni. + Primario + Secondario + Tonalità + Saturazione + Luminosità + Colore esadecimale Esc Ins Canc @@ -2510,6 +2518,7 @@ In attesa della connessione USB Ethernet degli occhiali. Questo telefono potrebbe non renderla disponibile alle app. La connessione XREAL si è interrotta o ha restituito una risposta non supportata. Nuovo tentativo… Supporto sperimentale per 1S. Usa la modalità Follow e disattiva la stabilizzazione nel menu degli occhiali. Direzioni del tracciamento e modalità di visualizzazione devono ancora essere testate sul dispositivo. + Tracciamento sperimentale della testa per Pro 2. La regolazione di luminosità e volume e il cambio della modalità di visualizzazione non sono ancora supportati. Cardboard VR Modalità Cardboard Immagini per l\'occhio sinistro e destro, per un visore VR per telefono. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 143351f826..f1e78ddb83 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -1392,6 +1392,14 @@ 黒の背景に白の文字、選択・フォーカス・押下時には青を使用します。 エレクトリックネイビー より明るい青を、グレーではなくネイビー寄りの画面に使用します。 + グラデーション + 自分で選んだプライマリとセカンダリの色を、ボタンやハイライトにグラデーションで使います。 + プライマリ + セカンダリ + 色相 + 彩度 + 明度 + 16進カラー Esc Ins Del @@ -2476,6 +2484,7 @@ グラスの USB Ethernet 接続を待っています。このスマートフォンでは、アプリがこの接続を利用できない場合があります。 XREAL との接続が中断されたか、サポートされていない応答が返されました。再試行しています… 1S のサポートは試験運用中です。グラスのメニューで Follow モードを使い、安定化をオフにしてください。トラッキングの方向と表示モードは、まだ実機でのテストが必要です。 + Pro 2 のヘッドトラッキングは試験運用中です。明るさと音量の調整、および表示モードの切り替えにはまだ対応していません。 開発元 パブリッシャー 発売日 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 901a84e7da..6b7efb33ad 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -1392,6 +1392,14 @@ 검은색 배경에 흰색 글자, 선택·포커스·누름 상태에는 파란색을 사용합니다. 일렉트릭 네이비 회색 대신 네이비 톤의 화면에 더 밝은 파란색을 사용합니다. + 그라데이션 + 직접 고른 기본색과 보조색이 버튼과 강조 표시에 섞여 적용됩니다. + 기본색 + 보조색 + 색조 + 채도 + 명도 + 16진수 색상 Esc Ins Del @@ -2476,6 +2484,7 @@ 안경의 USB Ethernet 연결을 기다리는 중입니다. 이 휴대폰은 앱에 이 연결을 제공하지 않을 수 있습니다. XREAL 연결이 중단되었거나 지원되지 않는 응답을 받았습니다. 다시 시도하는 중… 1S 지원은 실험 단계입니다. 안경 메뉴에서 Follow 모드를 사용하고 안정화를 끄세요. 트래킹 방향과 디스플레이 모드는 아직 기기에서 테스트가 필요합니다. + Pro 2 헤드 트래킹은 실험 단계입니다. 밝기와 음량 조절 및 디스플레이 모드 전환은 아직 지원되지 않습니다. 개발사 배급사 출시일 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 6c5acab203..ef8c7d5f22 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -1390,6 +1390,14 @@ Latar hitam, teks putih, biru untuk semua yang dipilih, difokus atau ditekan. Navy elektrik Biru lebih cerah, pada permukaan yang lebih cenderung navy daripada kelabu. + Kecerunan + Warna utama dan sekunder pilihan anda, diadun pada butang dan sorotan. + Utama + Sekunder + Rona + Ketepuan + Kecerahan + Warna hex Esc Ins Del @@ -2474,6 +2482,7 @@ Menunggu sambungan USB Ethernet cermin mata. Telefon ini mungkin tidak mendedahkannya kepada apl. Sambungan XREAL terganggu atau memberikan respons yang tidak disokong. Mencuba semula… Sokongan eksperimen untuk 1S. Gunakan mod Follow dan matikan penstabilan dalam menu cermin mata. Arah penjejakan dan mod paparan masih perlu diuji pada peranti. + Penjejakan kepala Pro 2 secara eksperimen. Pelarasan kecerahan, kelantangan dan pertukaran mod paparan belum disokong. Cardboard VR Mod Cardboard Paparan mata kiri dan kanan untuk kaca mata VR telefon. diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 6bbab58190..5dc36a00c5 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -1404,6 +1404,14 @@ Svart bakgrunn, hvit skrift, det blå for alt som er valgt, fokusert eller trykket. Elektrisk marineblå Det blå lysere, på flater som lener mer mot marineblått enn grått. + Gradient + Dine egne primær- og sekundærfarger, blandet på knapper og uthevinger. + Primær + Sekundær + Fargetone + Metning + Lysstyrke + Hex-farge Esc Ins Del @@ -2499,6 +2507,7 @@ Venter på USB Ethernet-tilkoblingen til brillene. Denne telefonen gjør den kanskje ikke tilgjengelig for apper. XREAL-tilkoblingen ble avbrutt eller ga et svar som ikke støttes. Prøver igjen… Eksperimentell støtte for 1S. Bruk Follow-modus og slå av stabilisering i brillemenyen. Sporingsretninger og visningsmoduser må fortsatt testes på enheten. + Eksperimentell hodesporing for Pro 2. Justering av lysstyrke og volum samt bytte av visningsmodus støttes ikke ennå. Cardboard VR Cardboard-modus Bilder for venstre og høyre øye til en VR-brille for mobil. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 12400b3e86..02b1493d52 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1404,6 +1404,14 @@ Zwarte achtergrond, witte tekst, het blauw voor alles wat geselecteerd, gefocust of ingedrukt is. Elektrisch marineblauw Het blauw feller, op vlakken die naar marineblauw neigen in plaats van grijs. + Kleurverloop + Je eigen primaire en secundaire kleur, doorlopend op knoppen en accenten. + Primair + Secundair + Tint + Verzadiging + Helderheid + Hex-kleur Esc Ins Del @@ -2499,6 +2507,7 @@ Wachten op de USB Ethernet-verbinding van de bril. Deze telefoon maakt die mogelijk niet beschikbaar voor apps. De XREAL-verbinding is onderbroken of gaf een niet-ondersteund antwoord. Opnieuw proberen… Experimentele ondersteuning voor 1S. Gebruik de Follow-modus en schakel stabilisatie uit in het menu van de bril. Trackingrichtingen en weergavemodi moeten nog op een apparaat worden getest. + Experimentele hoofdtracking voor Pro 2. Het aanpassen van helderheid en volume en het wisselen van weergavemodus worden nog niet ondersteund. Cardboard VR Cardboard-modus Beelden voor linker- en rechteroog voor een VR-bril voor je telefoon. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index d80cd8cec9..a135e012d7 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1432,6 +1432,14 @@ Czarne tło, biały tekst i niebieski dla wszystkiego, co zaznaczone, aktywne lub naciśnięte. Elektryczny granat Jaśniejszy niebieski na powierzchniach wpadających w granat zamiast w szarość. + Gradient + Własny kolor podstawowy i dodatkowy, płynnie przechodzące na przyciskach i wyróżnieniach. + Podstawowy + Dodatkowy + Odcień + Nasycenie + Jasność + Kolor hex Esc Ins Del @@ -2552,6 +2560,7 @@ Oczekiwanie na połączenie USB Ethernet okularów. Ten telefon może nie udostępniać go aplikacjom. Połączenie z XREAL zostało przerwane lub zwróciło nieobsługiwaną odpowiedź. Ponawianie… Eksperymentalna obsługa 1S. Użyj trybu Follow i wyłącz stabilizację w menu okularów. Kierunki śledzenia i tryby wyświetlania wymagają jeszcze testów na urządzeniu. + Eksperymentalne śledzenie ruchów głowy dla Pro 2. Regulacja jasności i głośności oraz przełączanie trybu wyświetlania nie są jeszcze obsługiwane. Cardboard VR Tryb Cardboard Obraz dla lewego i prawego oka do gogli VR na telefon. diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index fed2cf78ec..b29e753e2d 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -1407,6 +1407,14 @@ Fundo preto, texto branco e o azul para tudo o que está selecionado, focado ou premido. Azul-marinho elétrico O azul mais vivo, em superfícies que tendem para o azul-marinho em vez do cinzento. + Gradiente + As suas próprias cores primária e secundária, combinadas nos botões e destaques. + Primária + Secundária + Matiz + Saturação + Brilho + Cor hexadecimal Esc Ins Del @@ -2510,6 +2518,7 @@ A aguardar a ligação Ethernet por USB dos óculos. Este telemóvel pode não a disponibilizar às apps. A ligação aos óculos XREAL foi interrompida ou devolveu uma resposta não suportada. A tentar novamente… Suporte experimental para os 1S. Utilize o modo Follow e desative a estabilização no menu dos óculos. As direções de seguimento e os modos de ecrã ainda têm de ser testados no dispositivo. + Seguimento experimental dos movimentos da cabeça para Pro 2. O ajuste do brilho e do volume e a mudança do modo de ecrã ainda não são suportados. Cardboard VR Modo Cardboard Imagens para o olho esquerdo e o direito, para uns óculos de RV para telemóvel. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 37559d301f..79239e0c5a 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1407,6 +1407,14 @@ Fundo preto, texto branco e o azul em tudo que estiver selecionado, em foco ou pressionado. Marinho elétrico O azul mais vivo, sobre superfícies puxadas para o marinho em vez do cinza. + Gradiente + Suas próprias cores primária e secundária, combinadas em botões e destaques. + Primária + Secundária + Matiz + Saturação + Brilho + Cor hexadecimal Esc Ins Del @@ -2510,6 +2518,7 @@ Aguardando a conexão Ethernet por USB dos óculos. Este celular pode não disponibilizá-la para os apps. A conexão com os óculos XREAL foi interrompida ou retornou uma resposta incompatível. Tentando novamente… Suporte experimental ao 1S. Use o modo Follow e desative a estabilização no menu dos óculos. As direções do rastreamento e os modos de exibição ainda precisam de testes no dispositivo. + Rastreamento experimental da cabeça para Pro 2. Os ajustes de brilho e volume e a troca do modo de exibição ainda não são compatíveis. Cardboard VR Modo Cardboard Imagens para o olho esquerdo e o direito, para um óculos de RV de celular. diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 5ddf3f0a59..c0736cfe0c 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -1418,6 +1418,14 @@ Fundal negru, text alb, albastrul pentru tot ce este selectat, focalizat sau apăsat. Bleumarin electric Albastrul mai strălucitor, pe suprafețe care tind spre bleumarin în loc de gri. + Gradient + Culorile tale primară și secundară, combinate pe butoane și evidențieri. + Primară + Secundară + Nuanță + Saturație + Luminozitate + Culoare hex Esc Ins Del @@ -2524,6 +2532,7 @@ Se așteaptă conexiunea USB Ethernet a ochelarilor. Este posibil ca acest telefon să nu o expună aplicațiilor. Conexiunea XREAL a fost întreruptă sau a returnat un răspuns neacceptat. Se reîncearcă… Suport experimental pentru 1S. Folosește modul Follow și dezactivează stabilizarea din meniul ochelarilor. Direcțiile de urmărire și modurile de afișare trebuie încă testate pe dispozitiv. + Urmărire experimentală a mișcărilor capului pentru Pro 2. Reglarea luminozității și a volumului și schimbarea modului de afișare nu sunt încă acceptate. Cardboard VR Mod Cardboard Imagini pentru ochiul stâng și cel drept, pentru un vizor VR pentru telefon. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 83295afb97..6e4145bb3a 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1431,6 +1431,14 @@ Черный фон, белый текст, синий — для всего выбранного, активного или нажатого. Электрик Более яркий синий на поверхностях темно-синего, а не серого оттенка. + Градиент + Ваши основной и дополнительный цвета, плавно переходящие на кнопках и выделениях. + Основной + Дополнительный + Оттенок + Насыщенность + Яркость + Цвет hex Esc Ins Del @@ -2545,6 +2553,7 @@ Ожидание подключения очков по USB Ethernet. Этот телефон может не предоставлять его приложениям. Подключение к XREAL прервано или получен неподдерживаемый ответ. Повторная попытка… Экспериментальная поддержка 1S. Включите режим Follow и отключите стабилизацию в меню очков. Направления отслеживания и режимы отображения ещё нужно проверить на устройстве. + Экспериментальное отслеживание движений головы для Pro 2. Настройка яркости и громкости и переключение режимов отображения пока не поддерживаются. Разработчик Издатель Дата выхода diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 3bab33523f..1da71dc1cb 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -1404,6 +1404,14 @@ Svart bakgrund, vit text, den blå färgen för allt som är markerat, i fokus eller nedtryckt. Elektrisk marinblå Den blå färgen klarare, på ytor som lutar åt marinblått i stället för grått. + Gradient + Dina egna primära och sekundära färger, blandade på knappar och markeringar. + Primär + Sekundär + Nyans + Mättnad + Ljusstyrka + Hex-färg Esc Ins Del @@ -2499,6 +2507,7 @@ Väntar på glasögonens USB Ethernet-anslutning. Telefonen kanske inte gör den tillgänglig för appar. XREAL-anslutningen avbröts eller gav ett svar som inte stöds. Försöker igen… Experimentellt stöd för 1S. Använd Follow-läget och stäng av stabiliseringen i glasögonens meny. Spårningsriktningar och visningslägen behöver fortfarande testas på enheten. + Experimentell huvudspårning för Pro 2. Justering av ljusstyrka och volym samt byte av visningsläge stöds inte ännu. Cardboard VR Cardboard-läge Bilder för vänster och höger öga till ett VR-headset för mobilen. diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 6210877843..75dc4f5726 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -1390,6 +1390,14 @@ พื้นดำ ตัวอักษรขาว สีฟ้าสำหรับทุกสิ่งที่ถูกเลือก โฟกัส หรือกด กรมท่าไฟฟ้า สีฟ้าสว่างขึ้น บนพื้นผิวที่เอียงไปทางกรมท่ามากกว่าเทา + ไล่เฉดสี + สีหลักและสีรองที่คุณเลือกเอง ผสมกันบนปุ่มและส่วนที่เน้น + สีหลัก + สีรอง + เฉดสี + ความอิ่มตัว + ความสว่าง + สีเลขฐานสิบหก Esc Ins Del @@ -2474,6 +2482,7 @@ กำลังรอการเชื่อมต่อ USB Ethernet ของแว่นตา โทรศัพท์นี้อาจไม่เปิดให้แอปเข้าถึงการเชื่อมต่อนี้ การเชื่อมต่อ XREAL ขาดหายหรือได้รับการตอบกลับที่ไม่รองรับ กำลังลองใหม่… รองรับ 1S แบบทดลอง ใช้โหมด Follow และปิดการกันสั่นในเมนูของแว่นตา ทิศทางการติดตามและโหมดการแสดงผลยังต้องทดสอบกับอุปกรณ์จริง + การติดตามศีรษะแบบทดลองสำหรับ Pro 2 ยังไม่รองรับการปรับความสว่าง ระดับเสียง และการสลับโหมดการแสดงผล Cardboard VR โหมด Cardboard ภาพสำหรับตาซ้ายและตาขวาสำหรับแว่น VR ของโทรศัพท์ diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 33107674ae..da288eb3ee 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -1159,6 +1159,8 @@ Otomatik olarak PiP moduna geç Açılmış ekrandaki kontroller Cihaz açıkken oyun, Steam Deck dokunmatik yüzeylerinin ve arka tutamaklarının üstünde durur. Katlıyken oyun tam ekran olur. + Kumanda bağlıyken de göster + Telefonu tutan kumandalar için, kumanda bağlıyken de açılmış ekrandaki kontrolleri gösterir. Askıya alındı Pencere içinde pencere, oturum hazır olduğunda kullanılabilir. Android ayarlarında DroidDeck için pencere içinde pencereye izin verin. @@ -1393,6 +1395,14 @@ Siyah zemin, beyaz yazı; seçilen, odaklanan veya basılan her şey için mavi. Elektrik laciverti Daha parlak mavi; gri yerine laciverte çalan yüzeylerde. + Geçiş + Kendi birincil ve ikincil renklerin, düğmelerde ve vurgularda harmanlanır. + Birincil + İkincil + Ton + Doygunluk + Parlaklık + Hex rengi Esc Ins Del @@ -2485,6 +2495,7 @@ Gözlüğün USB Ethernet bağlantısı bekleniyor. Bu telefon bu bağlantıyı uygulamalara açmıyor olabilir. XREAL bağlantısı kesildi veya desteklenmeyen bir yanıt döndü. Yeniden deneniyor… Deneysel 1S desteği. Gözlük menüsünde Follow modunu kullanın ve görüntü sabitlemeyi kapatın. Takip yönlerinin ve ekran modlarının hâlâ cihazda test edilmesi gerekiyor. + Pro 2 için deneysel baş takibi. Parlaklık ve ses düzeyi ayarı ile ekran modu değiştirme henüz desteklenmiyor. Cardboard VR Cardboard modu Telefon VR gözlüğü için sol ve sağ göz görüntüleri. diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 5bc3cd8f11..002514a82a 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -1432,6 +1432,14 @@ Чорне тло, білий текст і синій для всього вибраного, у фокусі чи натиснутого. Електричний темно-синій Яскравіший синій на поверхнях із темно-синім відтінком замість сірого. + Градієнт + Ваші основний і додатковий кольори, що плавно переходять на кнопках і виділеннях. + Основний + Додатковий + Відтінок + Насиченість + Яскравість + Колір hex Esc Ins Del @@ -2549,6 +2557,7 @@ Очікування з’єднання USB Ethernet від окулярів. Цей телефон може не надавати його додаткам. З’єднання з XREAL перервалося або повернуло непідтримувану відповідь. Повторна спроба… Експериментальна підтримка 1S. Увімкніть режим Follow і вимкніть стабілізацію в меню окулярів. Напрямки відстеження й режими відображення ще потрібно перевірити на пристрої. + Експериментальне відстеження рухів голови для Pro 2. Налаштування яскравості й гучності та перемикання режимів відображення ще не підтримуються. Cardboard VR Режим Cardboard Зображення для лівого й правого ока для VR-окулярів під телефон. diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 874e91cd7b..14e1ffd7e4 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -1390,6 +1390,14 @@ Nền đen, chữ trắng, xanh cho mọi thứ được chọn, lấy nét hoặc nhấn. Xanh điện navy Màu xanh sáng hơn, trên các bề mặt nghiêng về navy thay vì xám. + Chuyển màu + Màu chính và màu phụ do bạn chọn, hòa trộn trên các nút và phần nổi bật. + Chính + Phụ + Sắc độ + Độ bão hòa + Độ sáng + Màu hex Esc Ins Del @@ -2474,6 +2482,7 @@ Đang chờ kết nối USB Ethernet của kính. Điện thoại này có thể không cho ứng dụng truy cập kết nối đó. Kết nối XREAL bị gián đoạn hoặc trả về phản hồi không được hỗ trợ. Đang thử lại… Hỗ trợ 1S thử nghiệm. Dùng chế độ Follow và tắt ổn định hình ảnh trong menu của kính. Hướng theo dõi và các chế độ hiển thị vẫn cần thử nghiệm trên thiết bị. + Theo dõi chuyển động đầu thử nghiệm cho Pro 2. Chưa hỗ trợ điều chỉnh độ sáng, âm lượng và chuyển chế độ hiển thị. Cardboard VR Chế độ Cardboard Hình cho mắt trái và mắt phải dành cho kính VR điện thoại. diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 960fdd825b..f95690ecf1 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1468,6 +1468,14 @@ 黑色背景、白色文字,选中、聚焦或按下的元素使用蓝色。 电光藏青 更明亮的蓝色,配以偏藏青而非灰色的界面。 + 渐变 + 你自己选择的主色和辅色,在按钮和高亮处渐变呈现。 + 主色 + 辅色 + 色相 + 饱和度 + 亮度 + 十六进制颜色 Esc Ins Del @@ -1877,6 +1885,7 @@ 不是 Adreno GPU 受支持 实验性:其驱动为测试构建 + Adreno 850 实验支持:需要配套的实验版显示驱动和游戏驱动;尚未在此设备上验证 低于已测试的硬件(Adreno 725 及更新):可能无法运行 不受支持:DroidDeck 需要 Adreno(骁龙)GPU @@ -2476,6 +2485,7 @@ 正在等待眼镜的 USB Ethernet 连接。这部手机可能不向应用开放此连接。 XREAL 连接中断或返回了不受支持的响应。正在重试… 实验性 1S 支持。请在眼镜菜单中使用跟随模式并关闭防抖。追踪方向和显示模式仍需在设备上测试。 + Pro 2 实验性头部追踪。暂不支持亮度、音量调节和显示模式切换。 开发商 发行商 发行日期 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 00c99dd55d..eab8f68379 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -1392,6 +1392,14 @@ 黑色背景、白色文字,所有已選取、焦點所在或按下的項目都使用藍色。 電光海軍藍 更明亮的藍色,搭配偏海軍藍而非灰色的介面。 + 漸層 + 你自行選擇的主色與輔色,在按鈕與強調處以漸層呈現。 + 主色 + 輔色 + 色相 + 飽和度 + 亮度 + 十六進位色彩 Esc Ins Del @@ -1801,6 +1809,7 @@ 不是 Adreno GPU 受支援 實驗性:其驅動程式為測試版本 + Adreno 850 實驗性支援:需要相容的實驗版顯示驅動程式及遊戲驅動程式;尚未在此裝置上驗證 低於已測試的硬件(Adreno 725 或更新):可能無法執行 不受支援:DroidDeck 需要 Adreno (Snapdragon) GPU @@ -2476,6 +2485,7 @@ 正在等候眼鏡的 USB Ethernet 連線。這部手機可能不會向應用程式開放此連線。 XREAL 連線中斷或傳回不支援的回應。正在重試… 實驗性 1S 支援。請在眼鏡選單中使用跟隨模式並關閉畫面穩定。追蹤方向和顯示模式仍需在裝置上測試。 + Pro 2 實驗性頭部追蹤。暫不支援亮度、音量調整及顯示模式切換。 開發商 發行商 發行日期 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 941437a04d..af4ac4b745 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -1392,6 +1392,14 @@ 黑色背景、白色文字,選取、聚焦或按下的項目使用藍色。 電光藏青 更亮的藍色,搭配偏藏青而非灰色的介面。 + 漸層 + 你自行選擇的主色與輔色,在按鈕與強調處以漸層呈現。 + 主色 + 輔色 + 色相 + 飽和度 + 亮度 + 十六進位色彩 Esc Ins Del @@ -1801,6 +1809,7 @@ 不是 Adreno GPU 受支援 實驗性:其驅動程式為測試版本 + Adreno 850 實驗性支援:需要相容的實驗版顯示驅動程式及遊戲驅動程式;尚未在此裝置上驗證 低於已測試的硬體(Adreno 725 及更新機型):可能無法執行 不受支援:DroidDeck 需要 Adreno(Snapdragon)GPU @@ -2476,6 +2485,7 @@ 正在等待眼鏡的 USB Ethernet 連線。這支手機可能不會向應用程式開放此連線。 XREAL 連線中斷或傳回不支援的回應。正在重試… 實驗性 1S 支援。請在眼鏡選單中使用跟隨模式並關閉畫面穩定。追蹤方向和顯示模式仍需在實機上測試。 + Pro 2 實驗性頭部追蹤。尚不支援亮度、音量調整及顯示模式切換。 開發商 發行商 發行日期 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 518b7d439c..8a165771ba 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1214,6 +1214,8 @@ Automatically enter PiP Controls on the unfolded screen Unfolded, the game sits above the Steam Deck trackpads and back grips. Folded, the game is full screen. + Keep them with a controller + Also show the unfolded controls while a controller is connected, for controllers that hold the phone. Suspended Picture in picture is available once the session is ready. Allow picture in picture for DroidDeck in Android settings. @@ -1463,6 +1465,14 @@ Black ground, white type, the blue for everything selected, focused or pressed. Electric navy The blue brighter, on surfaces that lean navy instead of grey. + Gradient + Your own primary and secondary colors, blended on buttons and highlights. + Primary + Secondary + Hue + Saturation + Brightness + Hex color Esc Ins Del @@ -1890,6 +1900,7 @@ Not an Adreno GPU Supported Experimental: its drivers are test builds + Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device Below tested hardware (Adreno 725 and newer): it may not run Not supported: DroidDeck needs an Adreno (Snapdragon) GPU @@ -2634,6 +2645,7 @@ Waiting for the glasses’ USB Ethernet connection. This phone may not expose it to apps. The XREAL connection was interrupted or returned an unsupported response. Retrying… Experimental 1S support. Use Follow mode and disable stabilization in the glasses menu. Tracking directions and display modes still need device testing. + Experimental Pro 2 head tracking. Brightness, volume, and display switching are not supported yet. Picture position Top Bottom diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesCallbacksTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesCallbacksTest.kt index 47f6b7a7cc..f2b097e748 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesCallbacksTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesCallbacksTest.kt @@ -13,6 +13,11 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config import org.robolectric.annotation.LooperMode +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.util.concurrent.CountDownLatch +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit @RunWith(RobolectricTestRunner::class) @Config(sdk = [28], manifest = Config.NONE) @@ -232,4 +237,95 @@ class GlassesCallbacksTest { field("sink").set(null, null) } } + + @Test fun pro2CallbacksUseSharedPoseAndRejectThePreviousConnection() { + fun v2(gen: Long) = Glasses::class.java.getDeclaredMethod("v2Listener", Long::class.javaPrimitiveType) + .apply { isAccessible = true }.invoke(Glasses, gen) as VitureV2Link.Listener + var delivered: FloatArray? = null + var timestamp = 0L + field("sink").set(null, Glasses.PoseSink { x, y, z, w, time -> + delivered = floatArrayOf(x, y, z, w) + timestamp = time + }) + try { + val q = floatArrayOf(0f, 0f, 0.6f, 0.8f) + v2(0).onPose(ByteArray(24), q, 100) + assertEquals(null, delivered) + v2(1).onPose(ByteArray(24), q, 101) + org.junit.Assert.assertArrayEquals(q, delivered, 0f) + assertEquals(101L, timestamp) + assertEquals(1L, field("imuPackets").getLong(null)) + v2(1).onValue(VitureProtocol.MSG_GET_DISPLAY, 0x32) + shadowOf(Looper.getMainLooper()).idle() + assertFalse(Glasses.state.value.sbs) + v2(1).onValue(VitureProtocol.MSG_GET_BRIGHTNESS, 8) + v2(1).onReady() + v2(1).onTracking(true) + v2(1).onLost() + generation(2) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(2, Glasses.state.value.brightness) + assertTrue(Glasses.state.value.connected) + assertFalse(Glasses.state.value.supportsScreen3dof) + assertFalse(Glasses.state.value.tracking) + } finally { field("sink").set(null, null) } + } + + @Test fun pro2DemandEndingBeforeTheFirstRestartPoseStillStopsTheStream() { + val writes = LinkedBlockingQueue() + val incoming = LinkedBlockingQueue() + val firstPose = CountDownLatch(1) + val firstRead = CountDownLatch(1) + val delegate = Glasses::class.java.getDeclaredMethod("v2Listener", Long::class.javaPrimitiveType) + .apply { isAccessible = true }.invoke(Glasses, 1L) as VitureV2Link.Listener + val listener = object : VitureV2Link.Listener by delegate { + override fun onPose(raw: ByteArray, q: FloatArray, timeNs: Long) { + delegate.onPose(raw, q, timeNs) + firstPose.countDown() + } + } + val transport = object : VitureV2Link.Transport { + override fun write(packet: ByteArray): Boolean { writes += packet; return true } + override fun read(timeoutMs: Long): VitureV2Link.Received? { + firstRead.countDown() + return incoming.poll(timeoutMs, TimeUnit.MILLISECONDS) + } + override fun close() {} + } + fun expectStream(stream: Int) = org.junit.Assert.assertArrayEquals( + VitureV2Protocol.imuControl(stream), writes.poll(2, TimeUnit.SECONDS)) + fun updateImu() = Glasses::class.java.getDeclaredMethod("updateImu") + .apply { isAccessible = true }.invoke(Glasses) + val link = VitureV2Link(transport, listener) + field("link").set(null, link) + field("sink").set(null, null) + try { + expectStream(VitureV2Protocol.STREAM_POSE) + assertTrue("Bootstrap write did not complete", firstRead.await(2, TimeUnit.SECONDS)) + val payload = ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN) + .putInt(0).putInt(1).putFloat(1f).putFloat(0f).putFloat(0f).putFloat(0f).array() + incoming += VitureV2Link.Received(VitureV2Protocol.packet(VitureV2Protocol.EVENT_POSE, payload), System.nanoTime()) + assertTrue(firstPose.await(2, TimeUnit.SECONDS)) + shadowOf(Looper.getMainLooper()).idle() + expectStream(VitureV2Protocol.STREAM_OFF) + assertTrue(Glasses.state.value.supportsScreen3dof) + assertFalse(Glasses.state.value.tracking) + + field("sink").set(null, Glasses.PoseSink { _, _, _, _, _ -> }) + updateImu() + assertFalse(Glasses.state.value.tracking) + field("sink").set(null, null) + updateImu() + expectStream(VitureV2Protocol.STREAM_POSE) + expectStream(VitureV2Protocol.STREAM_OFF) + assertFalse(link.trackingActive) + assertFalse(Glasses.state.value.tracking) + } finally { + generation(2) + link.close() + field("link").set(null, null) + field("sink").set(null, null) + shadowOf(Looper.getMainLooper()).idle() + } + } } diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt index ae274cece1..225805dc65 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt @@ -155,6 +155,58 @@ class GlassesUsbTest { assertEquals(listOf(gt), manager.requests) } + @Test fun pro2RequestsPermissionWithoutTheSdkAndDoesNotClaimCompanionProducts() { + val pro2 = device(0x1301, name = "VITURE Luma Ultra") + manager.devices[pro2.deviceName] = pro2 + refresh(ask = true) + assertEquals("VITURE Pro 2", state.value.model) + assertTrue(state.value.controllable) + assertTrue(state.value.experimental) + assertFalse(state.value.hardwareControls) + assertFalse(state.value.supportsDisplayModeControl) + assertFalse(state.value.supportsScreen3dof) + assertFalse(state.value.supportsSpatial) + assertEquals(listOf(pro2), manager.requests) + assertEquals(null, Glasses.deviceModel(device(0x1301, 0x1234, "VITURE Pro 2"))) + assertEquals(null, Glasses.deviceModel(device(0x1102, name = "VITURE Pro 2"))) + assertEquals(null, Glasses.deviceModel(device(0x1302, name = "VITURE Pro 2"))) + val ultra = Glasses.deviceModel(device(0x1104)) as VitureProtocol.Model + assertEquals(VitureProtocol.Family.ULTRA, ultra.family) + assertTrue(ultra.needsSdk) + } + + @Test fun pro2PoseAvailabilityDoesNotEnableDisplayOrHardwareWrites() { + val pro2 = device(0x1301) + manager.devices[pro2.deviceName] = pro2 + manager.granted.add(pro2.deviceName) + val sent = mutableListOf() + field("linkDevice").set(null, pro2) + field("link").set(null, object : GlassesLink { + override val hasImu = true + override fun send(msgId: Int, payload: ByteArray): Boolean { sent += msgId; return true } + override fun close() {} + }) + try { + refresh() + assertTrue(state.value.canControl) + assertTrue(state.value.supportsScreen3dof) + assertFalse(state.value.can3d) + assertFalse(state.value.supportsDisplayModeControl) + assertFalse(state.value.hardwareControls) + assertEquals(0, state.value.brightnessMax) + assertEquals(0, state.value.volumeMax) + Glasses.sendMode(0x32) + Glasses.setBrightness(5) + Glasses.setVolume(5) + shadowOf(Looper.getMainLooper()).idle() + assertTrue(sent.isEmpty()) + } finally { + field("link").set(null, null) + field("linkDevice").set(null, null) + (field("handler").get(null) as Handler).removeCallbacksAndMessages(null) + } + } + @Test fun gtVendorRequestsPermissionAndRetainsMaxProductName() { val gt = device(0xaf50, 0x3941, "RayNeo GT MAX") manager.devices[gt.deviceName] = gt diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/VitureProtocolTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/VitureProtocolTest.kt index 565e8b6145..cefc2e9e42 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/VitureProtocolTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/VitureProtocolTest.kt @@ -130,6 +130,31 @@ class VitureProtocolTest { assertArrayEquals(floatArrayOf(0f, 0f, sin(half).toFloat(), cos(half).toFloat()), q, 1e-5f) } + @Test fun directPro2KeepsSdkOnlyFamiliesAndUnknownProductsIsolated() { + val direct = VitureProtocol.model(0x1301, "VITURE Luma Ultra")!! + assertEquals("VITURE Pro 2", direct.name) + assertEquals(VitureProtocol.Family.PRO2, direct.family) + assertFalse(direct.needsSdk) + assertFalse(direct.hardwareControls) + assertFalse(direct.supportsDisplayModeControl) + assertFalse(direct.hasSunblock) + assertEquals(0, direct.brightnessMax) + assertEquals(0, direct.volumeMax) + + for (pid in listOf(0x1101, 0x1104, 0x1201, 0x1211)) { + val model = VitureProtocol.model(pid, null)!! + assertTrue(model.needsSdk) + assertTrue(model.hardwareControls) + assertTrue(model.supportsDisplayModeControl) + } + assertNull(VitureProtocol.model(0x1102, "VITURE Pro 2")) + assertNull(VitureProtocol.model(0x1302, "VITURE Pro 2")) + val sdk = VitureProtocol.sdkModel("Pro 2")!! + assertTrue(sdk.needsSdk) + assertTrue(sdk.hardwareControls) + assertTrue(sdk.supportsDisplayModeControl) + } + @Test fun imuFallsBackToEuler() { val payload = ByteBuffer.allocate(12).putFloat(0f).putFloat(0f).putFloat(30f).array() val q = VitureProtocol.imuQuaternion(payload)!! diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/VitureV2LinkTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/VitureV2LinkTest.kt new file mode 100644 index 0000000000..475a0c4d44 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/glasses/VitureV2LinkTest.kt @@ -0,0 +1,404 @@ +package com.droiddeck.launcher.glasses + +import com.droiddeck.launcher.gpu.HeadPose +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.IOException +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicReference +import kotlin.math.sqrt + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class VitureV2LinkTest { + private val transport = FakeTransport() + private val listener = RecordingListener() + private var link: VitureV2Link? = null + + @After fun close() { link?.close() } + + @Test fun writeAndAckDoNotBecomeReadyWithoutAValidPose() { + val link = start() + transport.feed(ack()) + transport.feed(pose(1).also { it[8] = (it[8].toInt() xor 1).toByte() }) + transport.feed(pose(2, floatArrayOf(0f, 0f, 0f, 0f))) + transport.feed(VitureV2Protocol.packet(VitureV2Protocol.EVENT_RAW, ByteArray(56))) + transport.flush() + assertFalse(link.ready) + assertFalse(link.hasImu) + assertFalse(link.trackingActive) + assertEquals(0, listener.readyCount.get()) + assertTrue(listener.poses.isEmpty()) + assertEquals(2L, link.badFrames) + + val receiptTime = System.nanoTime() + val valid = pose(3) + transport.feed(valid, receiptTime) + transport.flush() + assertTrue(link.ready) + assertTrue(link.hasImu) + assertTrue(link.trackingActive) + assertEquals(1, listener.readyCount.get()) + assertEquals(listOf(true), listener.tracking) + assertEquals(1, listener.poses.size) + assertEquals(receiptTime, listener.poses.single().timeNs) + assertArrayEquals(valid, listener.poses.single().raw) + } + + @Test fun duplicatesAndBackwardTicksAreDroppedWhileUnsignedWrapAdvances() { + start() + for (tick in listOf(0xFFFFFFFEL, 0xFFFFFFFEL, 0xFFFFFFFDL, 0L, 0L, 0xFFFFFFFFL, 1L)) { + transport.feed(pose(tick)) + } + transport.flush() + assertEquals(3, listener.poses.size) + assertEquals(1, listener.readyCount.get()) + assertEquals(listOf(true), listener.tracking) + assertEquals(0L, link!!.badFrames) + } + + @Test fun poseCollectedDuringBootstrapWriteDoesNotEstablishReadiness() { + transport.collectDuringNextWrite(pose(1)) + val link = start() + assertFalse(link.ready) + assertFalse(link.trackingActive) + assertTrue(listener.poses.isEmpty()) + + transport.feed(pose(2)) + transport.flush() + assertTrue(link.ready) + assertTrue(link.trackingActive) + assertEquals(1, listener.readyCount.get()) + assertEquals(1, listener.poses.size) + } + + @Test fun poseCollectedDuringResumeWriteDoesNotRestartTracking() { + val link = startReady(100) + assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0))) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + transport.flush() + + transport.collectDuringNextWrite(pose(101)) + assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1))) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE)) + transport.flush() + assertFalse(link.trackingActive) + assertEquals(1, listener.poses.size) + + transport.feed(pose(102)) + transport.flush() + assertTrue(link.trackingActive) + assertEquals(2, listener.poses.size) + assertEquals(listOf(true, false, true), listener.tracking) + } + + @Test fun stoppingAndRestartingRequiresANewPoseAndRejectsQueuedOldSamples() { + val link = startReady(100) + assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0))) + assertFalse(link.trackingActive) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + transport.feed(pose(101)) + transport.feed(ack()) + transport.flush() + assertEquals(1, listener.poses.size) + assertTrue(link.ready) + assertFalse(link.trackingActive) + + val beforeRestart = System.nanoTime() + assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1))) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE)) + transport.feed(pose(102), beforeRestart) + transport.feed(ack()) + transport.flush() + assertFalse(link.trackingActive) + assertEquals(1, listener.poses.size) + + transport.feed(pose(0)) + transport.flush() + assertTrue(link.trackingActive) + assertEquals(2, listener.poses.size) + assertEquals(1, listener.readyCount.get()) + assertEquals(listOf(true, false, true), listener.tracking) + } + + @Test fun onReadyCanStopBootstrapBeforeTheFirstPoseIsForwarded() { + val link = start() + listener.whenReady = { assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0))) } + transport.feed(pose(1)) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + transport.flush() + assertEquals(1, listener.readyCount.get()) + assertTrue(link.ready) + assertFalse(link.trackingActive) + assertTrue(listener.poses.isEmpty()) + assertEquals(listOf(true, false), listener.tracking) + } + + @Test fun rapidStopStartCannotAcceptThePreviousStreamsPendingRead() { + val link = startReady() + val held = transport.hold(pose(2)) + try { + assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0))) + assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1))) + } finally { + held.release.countDown() + } + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE)) + transport.flush() + assertFalse(link.trackingActive) + assertEquals(1, listener.poses.size) + assertEquals(listOf(true, false), listener.tracking) + + transport.feed(pose(3)) + transport.flush() + assertTrue(link.trackingActive) + assertEquals(2, listener.poses.size) + } + + @Test fun onReadyCanCloseWithoutForwardingAPoseOrReportingLoss() { + val link = start() + listener.whenReady = link::close + transport.feed(pose(1)) + transport.awaitClosed() + assertFalse(link.ready) + assertFalse(link.trackingActive) + assertTrue(listener.poses.isEmpty()) + assertEquals(0, listener.lostCount.get()) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + } + + @Test fun unsupportedSettersNeverProduceWritesAndQueriesKeepGenericIds() { + val link = startReady() + for ((id, payload) in listOf( + VitureProtocol.MSG_BRIGHTNESS to byteArrayOf(3), + VitureProtocol.MSG_VOLUME to byteArrayOf(3), + VitureProtocol.MSG_DISPLAY to byteArrayOf(0x32), + VitureProtocol.MSG_FILM to byteArrayOf(1), + VitureProtocol.MSG_IMU_RATE to byteArrayOf(3), + VitureProtocol.MSG_IMU to byteArrayOf(2), + VitureProtocol.MSG_IMU to byteArrayOf(), + VitureProtocol.MSG_GET_VOLUME to byteArrayOf(1), + )) assertFalse("msgId=$id", link.send(id, payload)) + assertTrue(link.send(VitureProtocol.MSG_GET_IMU, byteArrayOf())) + transport.flush() + assertTrue(transport.writes.isEmpty()) + + val queries = listOf( + Triple(VitureProtocol.MSG_GET_BRIGHTNESS, VitureV2Protocol.MSG_GET_BRIGHTNESS, 3), + Triple(VitureProtocol.MSG_GET_VOLUME, VitureV2Protocol.MSG_GET_VOLUME, 5), + Triple(VitureProtocol.MSG_GET_DISPLAY, VitureV2Protocol.MSG_GET_DISPLAY, 0x31), + ) + for ((genericId, wireId, value) in queries) { + assertTrue(link.send(genericId, byteArrayOf())) + transport.expectWrite(VitureV2Protocol.packet(wireId)) + transport.feed(VitureV2Protocol.packet(wireId + VitureV2Protocol.RESPONSE_OFFSET, + byteArrayOf(0, value.toByte()))) + } + transport.feed(VitureV2Protocol.packet(VitureV2Protocol.MSG_GET_VOLUME + VitureV2Protocol.RESPONSE_OFFSET, + byteArrayOf(1, 7))) + transport.feed(VitureV2Protocol.packet(VitureV2Protocol.MSG_GET_VOLUME + VitureV2Protocol.RESPONSE_OFFSET, + byteArrayOf(0, 7, 8))) + transport.flush() + assertEquals(queries.map { it.first to it.third }, listener.values) + } + + @Test fun failureToWriteBootstrapClosesTransportAndReportsLoss() { + transport.failNextWrite.set(true) + val link = VitureV2Link(transport, listener).also { this.link = it } + transport.awaitClosed() + assertFalse(link.ready) + assertFalse(link.hasImu) + assertFalse(link.trackingActive) + assertEquals(0, listener.readyCount.get()) + assertEquals(1, listener.lostCount.get()) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE)) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + } + + @Test fun rejectedStreamAckClosesWithoutMarkingTrackingActive() { + val link = start() + transport.feed(ack(status = 7)) + transport.awaitClosed() + assertFalse(link.ready) + assertFalse(link.trackingActive) + assertEquals(1, listener.lostCount.get()) + assertEquals(0, listener.readyCount.get()) + assertTrue(listener.tracking.isEmpty()) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + } + + @Test fun readFailureClearsTrackingAndClosesTransport() { + val link = startReady() + transport.disconnect() + transport.awaitClosed() + assertFalse(link.ready) + assertFalse(link.trackingActive) + assertEquals(listOf(true, false), listener.tracking) + assertEquals(1, listener.lostCount.get()) + assertFalse(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1))) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + } + + @Test fun explicitCloseSendsOffOnceAndDoesNotReportLoss() { + val link = startReady() + link.close() + transport.awaitClosed() + assertFalse(link.ready) + assertFalse(link.trackingActive) + assertEquals(listOf(true, false), listener.tracking) + assertEquals(0, listener.lostCount.get()) + assertEquals(1, transport.closeCount.get()) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + link.close() + assertFalse(link.send(VitureProtocol.MSG_GET_BRIGHTNESS, byteArrayOf())) + assertEquals(1, transport.closeCount.get()) + assertTrue(transport.writes.isEmpty()) + } + + @Test fun sharedPoseProducesTheSourceRightUpBackRelativeRotation() { + startReady() + val baseline = listener.poses.single().q + val reference = HeadPose.recenter(HeadPose.fromGlasses(baseline[0], baseline[1], baseline[2], baseline[3]), + centerView = true) + val half = sqrt(0.5f) + val rotations = listOf( + floatArrayOf(half, half, 0f, 0f), + floatArrayOf(half, 0f, half, 0f), + floatArrayOf(half, 0f, 0f, half), + floatArrayOf(0.5f, -0.5f, 0.5f, -0.5f), + ) + rotations.forEachIndexed { index, q -> transport.feed(pose(index + 2L, q)) } + transport.flush() + for ((source, event) in rotations.zip(listener.poses.drop(1))) { + val q = event.q + val relative = HeadPose.relative(reference, HeadPose.fromGlasses(q[0], q[1], q[2], q[3])) + assertArrayEquals(HeadPose.fromQuaternion(source[1], source[2], source[3], source[0]), relative, 1e-5f) + } + assertEquals(rotations.size + 1, listener.poses.size) + } + + private fun start(): VitureV2Link = VitureV2Link(transport, listener).also { + link = it + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE)) + transport.flush() + } + + private fun startReady(tick: Long = 1): VitureV2Link = start().also { + transport.feed(pose(tick)) + transport.flush() + assertTrue(it.ready) + } + + private fun ack(status: Int = 0) = VitureV2Protocol.packet( + VitureV2Protocol.MSG_IMU_CONTROL + VitureV2Protocol.RESPONSE_OFFSET, byteArrayOf(status.toByte())) + + private fun pose(tick: Long, wxyz: FloatArray = floatArrayOf(1f, 0f, 0f, 0f)): ByteArray { + val payload = ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN) + .putInt(0x126).putInt(tick.toInt()) + wxyz.forEach(payload::putFloat) + return VitureV2Protocol.packet(VitureV2Protocol.EVENT_POSE, payload.array()) + } + + private data class PoseEvent(val raw: ByteArray, val q: FloatArray, val timeNs: Long) + + private class RecordingListener : VitureV2Link.Listener { + val readyCount = AtomicInteger() + val lostCount = AtomicInteger() + val tracking = CopyOnWriteArrayList() + val values = CopyOnWriteArrayList>() + val poses = CopyOnWriteArrayList() + @Volatile var whenReady: (() -> Unit)? = null + override fun onReady() { readyCount.incrementAndGet(); whenReady?.invoke() } + override fun onValue(msgId: Int, value: Int) { values += msgId to value } + override fun onPose(raw: ByteArray, q: FloatArray, timeNs: Long) { poses += PoseEvent(raw.copyOf(), q.copyOf(), timeNs) } + override fun onTracking(active: Boolean) { tracking += active } + override fun onLost() { lostCount.incrementAndGet() } + } + + private sealed interface ReadStep { + data class Packet(val received: VitureV2Link.Received) : ReadStep + data class Barrier(val reached: CountDownLatch) : ReadStep + data class HeldPacket( + val received: VitureV2Link.Received, + val entered: CountDownLatch = CountDownLatch(1), + val release: CountDownLatch = CountDownLatch(1), + ) : ReadStep + data object Disconnected : ReadStep + } + + private class FakeTransport : VitureV2Link.Transport { + val writes = LinkedBlockingQueue(64) + val closeCount = AtomicInteger() + val failNextWrite = AtomicBoolean() + private val collectedDuringWrite = AtomicReference() + private val incoming = LinkedBlockingQueue(128) + private val closed = CountDownLatch(1) + + override fun write(packet: ByteArray): Boolean { + check(writes.offer(packet.copyOf())) + val success = !failNextWrite.getAndSet(false) + if (success) collectedDuringWrite.getAndSet(null)?.let { feed(it, System.nanoTime()) } + return success + } + + override fun read(timeoutMs: Long): VitureV2Link.Received? = when ( + val step = incoming.poll(timeoutMs, TimeUnit.MILLISECONDS) + ) { + is ReadStep.Packet -> step.received + is ReadStep.Barrier -> { step.reached.countDown(); null } + is ReadStep.HeldPacket -> { + step.entered.countDown() + check(step.release.await(2, TimeUnit.SECONDS)) + step.received + } + ReadStep.Disconnected -> throw IOException("Device disconnected") + null -> null + } + + override fun close() { closeCount.incrementAndGet(); closed.countDown() } + + fun feed(packet: ByteArray, timeNs: Long = System.nanoTime()) { + check(incoming.offer(ReadStep.Packet(VitureV2Link.Received(packet.copyOf(), timeNs)))) + } + + fun collectDuringNextWrite(packet: ByteArray) { + check(collectedDuringWrite.compareAndSet(null, packet.copyOf())) + } + + fun disconnect() { check(incoming.offer(ReadStep.Disconnected)) } + + fun hold(packet: ByteArray): ReadStep.HeldPacket { + val held = ReadStep.HeldPacket(VitureV2Link.Received(packet.copyOf(), System.nanoTime())) + check(incoming.offer(held)) + assertTrue("Worker did not enter the held read", held.entered.await(2, TimeUnit.SECONDS)) + return held + } + + fun expectWrite(expected: ByteArray) { + assertArrayEquals(expected, writes.poll(2, TimeUnit.SECONDS)) + } + + fun flush() { + val reached = CountDownLatch(1) + check(incoming.offer(ReadStep.Barrier(reached))) + assertTrue("Worker did not consume queued reports", reached.await(2, TimeUnit.SECONDS)) + } + + fun awaitClosed() { assertTrue("Transport did not close", closed.await(2, TimeUnit.SECONDS)) } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/VitureV2ProtocolTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/VitureV2ProtocolTest.kt new file mode 100644 index 0000000000..95f0cfb551 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/glasses/VitureV2ProtocolTest.kt @@ -0,0 +1,175 @@ +// Fixtures 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 org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sqrt + +class VitureV2ProtocolTest { + @Test fun requestsMatchUpstreamWireExamples() { + assertArrayEquals(hex("10 00 01 03 02 00 03 00 01 02"), + VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE)) + assertArrayEquals(hex("10 00 01 03 02 00 04 00 02 02"), + VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_RAW)) + assertArrayEquals(hex("10 00 01 03 02 00 00 00 00 00"), + VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + assertArrayEquals(hex("10 00 22 31 00 00 00 00"), + VitureV2Protocol.packet(VitureV2Protocol.MSG_GET_BRIGHTNESS)) + } + + @Test fun requestBoundsAndStreamLimitsAreEnforced() { + assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.packet(-1) } + assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.packet(0x10000) } + assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.packet(0, ByteArray(57)) } + assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.imuControl(3) } + assertThrows(IllegalArgumentException::class.java) { + VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE, VitureV2Protocol.Rate.HZ_500) + } + assertArrayEquals(hex("10 00 01 03 02 00 07 00 02 05"), + VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_RAW, VitureV2Protocol.Rate.HZ_1000)) + val maximum = VitureV2Protocol.packet(0xFFFF, ByteArray(56) { 0xFF.toByte() }) + assertEquals(64, maximum.size) + assertEquals(0x37C8, (maximum[6].toInt() and 0xFF) or ((maximum[7].toInt() and 0xFF) shl 8)) + assertNotNull(VitureV2Protocol.parse(maximum)) + } + + @Test fun brightnessReplyMatchesUpstreamAndKeepsFailureStatus() { + val frame = VitureV2Protocol.parse(hex("10 00 22 51 02 00 03 00 00 03"))!! + val reply = VitureV2Protocol.reply(frame, VitureV2Protocol.MSG_GET_BRIGHTNESS)!! + assertTrue(reply.success) + assertEquals(0, reply.status) + assertArrayEquals(byteArrayOf(3), reply.body) + assertNull(VitureV2Protocol.reply(frame, VitureV2Protocol.MSG_GET_VOLUME)) + assertNull(VitureV2Protocol.reply(frame, -1)) + val failure = VitureV2Protocol.parse(hex("10 00 01 23 01 00 07 00 07"))!! + val failedReply = VitureV2Protocol.reply(failure, VitureV2Protocol.MSG_IMU_CONTROL)!! + assertFalse(failedReply.success) + assertEquals(7, failedReply.status) + assertTrue(failedReply.body.isEmpty()) + val noStatus = VitureV2Protocol.parse(hex("10 00 01 23 00 00 00 00"))!! + assertNull(VitureV2Protocol.reply(noStatus, VitureV2Protocol.MSG_IMU_CONTROL)) + } + + @Test fun validatesReceiveBoundsBeforeReadingHeader() { + val valid = hex("10 00 22 51 02 00 03 00 00 03") + for (size in listOf(-1, 0, 7, 9, 11, 65, Int.MAX_VALUE)) { + assertNull("size=$size", VitureV2Protocol.parse(valid, size)) + } + assertNull(VitureV2Protocol.parse(ByteArray(0))) + assertNull(VitureV2Protocol.parse(valid.copyOf(65))) + assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[0] = 0x11 })) + assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[1] = 1 })) + assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[6] = 0xFF.toByte() })) + assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[9] = 4 })) + } + + @Test fun rejectsOversizedAndTruncatedDeclaredPayloads() { + val valid = hex("10 00 22 51 02 00 03 00 00 03") + assertNull(VitureV2Protocol.parse(valid.copyOf(9))) + val tooLong = valid.copyOf(64).also { it[4] = 57 } + assertNull(VitureV2Protocol.parse(tooLong)) + tooLong[4] = 0xFF.toByte() + tooLong[5] = 0xFF.toByte() + assertNull(VitureV2Protocol.parse(tooLong)) + val padded = valid.copyOf(64) + val parsed = VitureV2Protocol.parse(padded)!! + assertArrayEquals(byteArrayOf(0, 3), parsed.payload) + padded[9] = 8 + assertArrayEquals(byteArrayOf(0, 3), parsed.payload) + } + + @Test fun poseFixturePreservesDeviceCounterAndConvertsWxyzToNormalizedXyzw() { + val frame = VitureV2Protocol.parse(hex( + "10 00 08 73 18 00 9c 08 " + + "26 01 00 00 59 d6 21 00 dd e3 2b 3e 52 5d 7c 3f dd 45 9a 3b e8 27 52 3a" + ))!! + val pose = VitureV2Protocol.pose(frame)!! + assertEquals(0x0021D659L, pose.deviceTick) + assertEquals(0x126L, pose.unknown) + val expected = floatArrayOf(Float.fromBits(0x3F7C5D52), Float.fromBits(0x3B9A45DD), + Float.fromBits(0x3A5227E8), Float.fromBits(0x3E2BE3DD)) + val norm = sqrt(expected.sumOf { it.toDouble() * it }).toFloat() + assertArrayEquals(expected.map { it / norm }.toFloatArray(), pose.quaternion, 1e-7f) + assertEquals(1.0, pose.quaternion.sumOf { it.toDouble() * it }, 1e-6) + } + + @Test fun poseNormalizesSmallScaleErrorsWithoutChangingAxesOrCounter() { + val payload = posePayload(0.5f, -0.5f, 0.5f, -0.5f) + ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).putInt(4, -1) + val pose = VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, payload))!! + assertEquals(0xFFFFFFFFL, pose.deviceTick) + assertArrayEquals(floatArrayOf(-0.5f, 0.5f, -0.5f, 0.5f), pose.quaternion, 0f) + val scaled = VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, posePayload(1.01f, 0f, 0f, 0f)))!! + assertArrayEquals(floatArrayOf(0f, 0f, 0f, 1f), scaled.quaternion, 1e-7f) + } + + @Test fun rejectsMalformedPoseAndInvalidQuaternions() { + val valid = posePayload(1f, 0f, 0f, 0f) + assertNull(VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_RAW, valid))) + for (size in listOf(0, 23, 25, 56)) { + assertNull(VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, valid.copyOf(size)))) + } + for (bad in listOf(0f, 0.5f, 2f, Float.MAX_VALUE, Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY)) { + assertNull("w=$bad", VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, posePayload(bad, 0f, 0f, 0f)))) + } + for (component in 1..3) { + val payload = valid.copyOf() + ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).putFloat(8 + component * 4, Float.NaN) + assertNull(VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, payload))) + } + } + + @Test fun rawReadsUnalignedFloatsAndPreservesUnknownBytes() { + val payload = rawPayload() + val frame = event(VitureV2Protocol.EVENT_RAW, payload) + val sample = VitureV2Protocol.raw(frame)!! + assertEquals(0xFFFFFFFEL, sample.deviceTick) + assertArrayEquals(floatArrayOf(1.5f, -2f, 0.25f), sample.gyroRadPerSec, 0f) + assertArrayEquals(floatArrayOf(0.0024f, -0.3221f, -0.9287f), sample.accelG, 0f) + assertArrayEquals(payload, sample.payload) + frame.payload.fill(0) + assertArrayEquals(payload, sample.payload) + } + + @Test fun rejectsMalformedRawAndNonfiniteMeasurementsButKeepsOpaqueTail() { + val payload = rawPayload() + assertNull(VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_POSE, payload))) + for (size in listOf(0, 24, 33, 34, 55)) { + assertNull(VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_RAW, payload.copyOf(size)))) + } + for (offset in listOf(10, 14, 18, 22, 26, 30)) { + for (bad in listOf(Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY)) { + val invalid = payload.copyOf() + ByteBuffer.wrap(invalid).order(ByteOrder.LITTLE_ENDIAN).putFloat(offset, bad) + assertNull("offset=$offset, value=$bad", VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_RAW, invalid))) + } + } + ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).putFloat(46, Float.NaN) + assertNotNull(VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_RAW, payload))) + } + + private fun event(msgId: Int, payload: ByteArray) = + VitureV2Protocol.parse(VitureV2Protocol.packet(msgId, payload))!! + + private fun posePayload(w: Float, x: Float, y: Float, z: Float) = + ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN) + .putInt(0x126).putInt(123).putFloat(w).putFloat(x).putFloat(y).putFloat(z).array() + + private fun rawPayload() = ByteBuffer.allocate(56).order(ByteOrder.LITTLE_ENDIAN) + .putInt(0x126).putInt(-2).putShort(187) + .putFloat(1.5f).putFloat(-2f).putFloat(0.25f) + .putFloat(0.0024f).putFloat(-0.3221f).putFloat(-0.9287f) + .putFloat(117.30f).putFloat(60.75f).putFloat(254.85f) + .put(byteArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).array() + + private fun hex(value: String) = value.split(' ').map { it.toInt(16).toByte() }.toByteArray() +} diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/GpuDetectionTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/GpuDetectionTest.kt index 6d64307e3f..bee21343dd 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/GpuDetectionTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/GpuDetectionTest.kt @@ -9,7 +9,7 @@ class GpuDetectionTest { private fun info(adreno: Boolean, model: Int) = GpuInfo(name = "x", model = model, family = GpuInfo.familyOf(adreno, model), soc = "", oneUi8Gen2 = false) - @Test fun modelIsTheFirstThreeDigitsOfWhateverTheKernelOrVulkanReports() { + @Test fun modelIsParsedOnlyFromAnAdrenoName() { assertEquals(650, GpuInfo.threeDigits("Adreno650")) assertEquals(830, GpuInfo.threeDigits("Adreno (TM) 830")) assertEquals(740, GpuInfo.threeDigits("Adreno740v2")) @@ -19,6 +19,12 @@ class GpuDetectionTest { assertEquals(0, GpuInfo.threeDigits(" ")) assertEquals(0, GpuInfo.threeDigits("Adreno")) assertEquals(0, GpuInfo.threeDigits("Adreno 65")) + assertEquals(850, GpuInfo.threeDigits("Adreno850v2")) + assertEquals(850, GpuInfo.threeDigits("Adreno (TM) 850")) + assertEquals(0, GpuInfo.threeDigits("44051431")) + assertEquals(0, GpuInfo.threeDigits("0x2a02be7")) + assertEquals(0, GpuInfo.threeDigits("Adreno 8500")) + assertEquals(0, GpuInfo.threeDigits("Mali-G850")) } @Test fun nonAdrenoRenderersAreNeverAdrenoWhateverNumberTheyCarry() { @@ -53,12 +59,14 @@ class GpuDetectionTest { assertEquals(Support.TESTED, info(true, 740).support) assertEquals(Support.TESTED, info(true, 750).support) assertEquals(Support.TESTED, info(true, 830).support) + assertEquals(Support.UNTESTED, info(true, 850).support) assertEquals(Support.UNSUPPORTED, info(false, 0).support) assertEquals(Support.UNSUPPORTED, info(false, 830).support) } @Test fun userFacingTextPerTier() { assertEquals("Supported", info(true, 830).supportText) + assertEquals("Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device", info(true, 850).supportText) assertEquals("Experimental: its drivers are test builds", info(true, 720).supportText) assertEquals("Outside tested hardware (Adreno 650, 725 and newer): it may not run", info(true, 618).supportText) assertEquals("Not supported: DroidDeck needs an Adreno (Snapdragon) GPU", info(false, 0).supportText) diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt index 0ce3bdc6cd..24a38bd75a 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt @@ -11,4 +11,61 @@ class GpuModelFallbackTest { assertEquals(0, GpuInfo.platformModel("somethingelse")) assertEquals(GpuInfo.Family.A7XX, GpuInfo.familyOf(true, GpuInfo.platformModel("pineapple"))) } + @Test fun sm8975IsTheOnlyNewSocFallback() { + assertEquals(850, GpuInfo.platformModel("unknown", "", "SM8975")) + assertEquals(850, GpuInfo.platformModel("unknown", "", "QTI SM8975")) + assertEquals(850, GpuInfo.platformModel("unknown", "QTI SM8975", "")) + assertEquals(850, GpuInfo.platformModel("unknown", "", " qti sm8975 ")) + assertEquals(0, GpuInfo.platformModel("unknown", "", "SM89750")) + assertEquals(0, GpuInfo.platformModel("unknown", "", "SM8975-PRO")) + assertEquals(0, GpuInfo.platformModel("unknown", "", "Qualcomm SM8975")) + assertEquals(0, GpuInfo.platformModel("unknown", "", "SM8850")) + assertEquals(850, GpuInfo.platformModel("sun", "", "SM8975")) + assertEquals(830, GpuInfo.platformModel("sun", "", "unknown")) + } + + @Test fun aKernelModelDoesNotNeedVulkanOrSocFallback() { + assertEquals(850 to "kernel", GpuInfo.modelFromNames("Adreno850v2", + { error("Vulkan must not be queried when the kernel identifies the GPU") }, + { error("SoC must not override the kernel model") })) + } + + @Test fun aMissingKernelModelUsesVulkanBeforeSocFallback() { + assertEquals(830 to "vulkan", GpuInfo.modelFromNames("Adreno", { "Adreno (TM) 830" }, + { error("SoC must not override the Vulkan model") })) + assertEquals(850 to "vulkan", GpuInfo.modelFromNames(null, { "Adreno850v2" }, { 0 })) + } + + @Test fun numericChipIdsCannotHideTheSocFallback() { + for (name in listOf(null, "", "Adreno", "44051431", "0x2a02be7")) { + assertEquals(850 to "platform", GpuInfo.modelFromNames(name, { "Adreno" }, + { GpuInfo.platformModel("unknown", "", "QTI SM8975") })) + } + assertEquals(0 to "", GpuInfo.modelFromNames(null, { null }, { 0 })) + } + + @Test fun sm8975StaysExperimentalWhenTheDriverReportsA840() { + val fallback = GpuInfo.platformModel("sun", "", "SM8975") + for (kernel in listOf("Adreno", "Adreno (TM) 840")) { + val (model, source) = GpuInfo.modelFromNames(kernel, { "Adreno (TM) 840" }, { fallback }) + val gpu = GpuInfo("Adreno $model", model, GpuInfo.familyOf(true, model), "SM8975", false, + modelSource = source, platformGpuModel = fallback) + assertEquals(840, gpu.model) + assertEquals(if (kernel == "Adreno") "vulkan" else "kernel", gpu.modelSource) + assertEquals(GpuInfo.Support.UNTESTED, gpu.support) + assertEquals("Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device", gpu.supportText) + } + } + + @Test fun anA840WithoutSm8975KeepsItsExistingSupportStatus() { + for (fallback in listOf(0, 830, 840)) { + val gpu = GpuInfo("Adreno 840", 840, GpuInfo.Family.A8XX, "", false, + platformGpuModel = fallback) + assertEquals(GpuInfo.Support.TESTED, gpu.support) + assertEquals("Supported", gpu.supportText) + } + val otherGpu = GpuInfo("Mali", 0, GpuInfo.Family.NOT_ADRENO, "", false, + platformGpuModel = 850) + assertEquals(GpuInfo.Support.UNSUPPORTED, otherGpu.support) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt index 8919b79a7c..963f9f739c 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt @@ -21,4 +21,13 @@ class SocNamesTest { assertEquals("Snapdragon 8 Gen 3 family (SG8350P)", SocNames.label("SG8350P", "pineapple")) assertEquals("XYZ123", SocNames.label("XYZ123", "")) } + @Test fun qtiPrefixIsNormalizedWithoutGuessingOtherModelVariants() { + assertEquals("Snapdragon 8 Elite Extreme Gen 6", SocNames.name("SM8975", "")) + assertEquals("Snapdragon 8 Elite Extreme Gen 6", SocNames.name("QTI SM8975", "")) + assertEquals("Snapdragon 8 Elite Extreme Gen 6", SocNames.name(" qti sm8975 ", "")) + assertEquals("Snapdragon 8 Elite Extreme Gen 6 (QTI SM8975)", SocNames.label("QTI SM8975", "")) + assertNull(SocNames.name("SM89750", "")) + assertNull(SocNames.name("SM8975-PRO", "")) + assertNull(SocNames.name("Qualcomm SM8975", "")) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/TurnipDriverAutoTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/TurnipDriverAutoTest.kt index b15e19630c..95713589ea 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/TurnipDriverAutoTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/TurnipDriverAutoTest.kt @@ -30,4 +30,17 @@ class TurnipDriverAutoTest { @Test fun otherDevicesRetainTheGenericFallback() { assertEquals("turnip25.1.0", TurnipDriver(RuntimeEnvironment.getApplication()).autoId()) } + + @Test fun normalizedGpuModelsSelectExistingGenerationDrivers() { + for (sdk in listOf(28, 36)) { + assertEquals("turnip26.3.0-a6xx", TurnipDriver.chooseByModel(650, sdk)) + assertEquals("turnip25.1.0", TurnipDriver.chooseByModel(730, sdk)) + assertEquals("turnip-sdk36", TurnipDriver.chooseByModel(850, sdk)) + } + } + + @Test fun unknownGpuModelsRetainTheSdkFallback() { + assertEquals("turnip25.1.0", TurnipDriver.chooseByModel(0, 28)) + assertEquals("turnip-sdk36", TurnipDriver.chooseByModel(0, 36)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt index a68458125e..48d77d0b0d 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt @@ -40,6 +40,33 @@ class SessionDisplayTest { assertEquals(864, SessionDisplay.unfoldedGameHeight(1920, 1080)) } + private fun unfoldedWanted( + enabled: Boolean = true, + controller: Boolean = false, + keepWithController: Boolean = false, + foldable: Boolean = true, + steamDeckPad: Boolean = true, + pip: Boolean = false, + smallestWidthDp: Int = 700, + ) = SessionDisplay.unfoldedControlsWanted(enabled, foldable, controller, keepWithController, steamDeckPad, pip, + 2448, 1848, smallestWidthDp) + + @Test fun unfoldedControlsHideForAControllerUnlessKeptWithOne() { + assertTrue(unfoldedWanted()) + assertFalse(unfoldedWanted(controller = true)) + assertTrue(unfoldedWanted(controller = true, keepWithController = true)) + assertTrue(unfoldedWanted(keepWithController = true)) + } + + @Test fun keepingUnfoldedControlsWithAControllerLeavesTheOtherConditions() { + assertFalse(unfoldedWanted(enabled = false, controller = true, keepWithController = true)) + assertFalse(unfoldedWanted(foldable = false, keepWithController = true)) + assertFalse(unfoldedWanted(steamDeckPad = false, keepWithController = true)) + assertFalse(unfoldedWanted(pip = true, keepWithController = true)) + assertFalse(unfoldedWanted(smallestWidthDp = 599, keepWithController = true)) + assertFalse(SessionDisplay.unfoldedControlsWanted(true, true, true, true, true, false, 0, 1848, 700)) + } + @Test fun followScreenKeepsTheWindowShapeAndSkipsTinyWindows() { assertEquals(2520 to 1080, SessionDisplay.resolveChoice(1080 to 2520, SessionDisplay.FOLLOW_SCREEN)) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionVisibilityPolicyTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionVisibilityPolicyTest.kt new file mode 100644 index 0000000000..708241662e --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionVisibilityPolicyTest.kt @@ -0,0 +1,27 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class SessionVisibilityPolicyTest { + @Test fun handsetScreenStateControlsActivityOnDefaultDisplay() { + assertFalse(SessionVisibilityPolicy.isHidden(true, true, true, false)) + assertTrue(SessionVisibilityPolicy.isHidden(true, false, true, true)) + } + + @Test fun externalDisplayStateControlsActivityIndependentlyOfHandset() { + assertFalse(SessionVisibilityPolicy.isHidden(true, false, false, true)) + assertTrue(SessionVisibilityPolicy.isHidden(true, true, false, false)) + } + + @Test fun missingActivityDisplayIsHiddenUntilActivityMoves() { + assertTrue(SessionVisibilityPolicy.isHidden(true, true, false, false)) + assertFalse(SessionVisibilityPolicy.isHidden(true, true, true, false)) + } + + @Test fun stoppedActivityIsHiddenButVisibleXrKeepsSessionVisible() { + assertTrue(SessionVisibilityPolicy.isHidden(false, true, true, true)) + assertFalse(SessionVisibilityPolicy.isHidden(false, false, true, false, xrActivityVisible = true)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt index fce0e6e544..29a1fc2a6a 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SettingsResetTest.kt @@ -27,6 +27,7 @@ class SettingsResetTest { @Test fun settingsGoBackToTheirDefaults() { SessionPrefs.setTheme(app, "ocean") + SessionPrefs.setUnfoldedControlsWithController(app, true) SessionPrefs.setNoXalia(app, false) SessionPrefs.setFpsLimit(app, SessionService.MODE_STEAM, 30) SessionPrefs.setHdr(app, SessionService.MODE_DESKTOP, true) @@ -46,6 +47,7 @@ class SettingsResetTest { assertTrue(SettingsReset.resetAll(app, gameProfiles = false)) assertEquals("graphite", SessionPrefs.theme(app)) + assertFalse(SessionPrefs.unfoldedControlsWithController(app)) assertTrue(SessionPrefs.noXalia(app)) assertEquals(0, SessionPrefs.fpsLimit(app, SessionService.MODE_STEAM)) assertFalse(SessionPrefs.hdr(app, SessionService.MODE_DESKTOP)) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GlassesPanelTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GlassesPanelTest.kt index 701d9d1635..97d0496769 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/GlassesPanelTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/GlassesPanelTest.kt @@ -30,6 +30,21 @@ import org.robolectric.annotation.Config class GlassesPanelTest { @get:Rule val compose = createRobolectricComposeRule() + @Test fun trackingOnlyDeviceHidesDisplayWritesButKeepsHeadTracking() { + show(supportsDisplayModeControl = false) + compose.onNodeWithTag("setting-glasses-hz").assertDoesNotExist() + compose.onNodeWithTag("setting-glasses-resolution-two_d").assertDoesNotExist() + compose.onNodeWithTag("setting-glasses-3d").assertDoesNotExist() + compose.onNodeWithTag("setting-glasses-3dof").assertExists() + } + + @Test fun trackingOnlyDeviceHidesVrDisplayWrites() { + show(supportsDisplayModeControl = false, tab = GlassesTab.VR, steamVrRunning = true) + compose.onNodeWithTag("setting-glasses-resolution-vr").assertDoesNotExist() + compose.onNodeWithTag("setting-glasses-3d-hz").assertDoesNotExist() + compose.onNodeWithTag("setting-glasses-auto3d").assertDoesNotExist() + } + @Test fun flatResolutionMenuShowsPerEyeResolutionsBesideRefresh() { show() compose.onNodeWithTag("setting-glasses-hz").assertExists() @@ -397,6 +412,7 @@ class GlassesPanelTest { outputActive: Boolean = inSession, controlAvailable: Boolean = true, supportsScreen3dof: Boolean = true, + supportsDisplayModeControl: Boolean = true, supportsSpatial: Boolean = false, supports30Hz: Boolean = false, sbs90: Boolean = true, @@ -406,6 +422,7 @@ class GlassesPanelTest { onRecenter: (() -> Unit)? = {}, ) { val state = GlassesState(present = true, connected = controlAvailable, controllable = true, + supportsDisplayModeControl = supportsDisplayModeControl, displayId = Display.DEFAULT_DISPLAY + 1, width = if (stereo) 3840 else 1920, height = 1200, model = "VITURE Luma Ultra", sbs = stereo, sbs90 = sbs90, supportsScreen3dof = supportsScreen3dof, supports30Hz = supports30Hz, supportsSpatial = supportsSpatial, resolutions = listOf( diff --git a/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt new file mode 100644 index 0000000000..5332c83ab0 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt @@ -0,0 +1,100 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.* +import androidx.compose.foundation.layout.size +import androidx.compose.ui.unit.dp +import org.junit.Rule +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class NavigationSelectionTest { + @get:Rule val compose = createRobolectricComposeRule() + + @Before fun controlAnimationFrames() { + compose.mainClock.autoAdvance = false + } + + @Test fun tabStripAnnouncesSelectionAndUpdatesAfterClick() { + val selected = mutableIntStateOf(0) + compose.setContent { DroidDeckTheme { TabStrip(listOf("First", "Second"), selected.intValue, { selected.intValue = it }) } } + verify("First", "Second") + } + + @Test fun sheetChipsAnnounceSelectionAndUpdateAfterClick() { + val selected = mutableIntStateOf(0) + compose.setContent { DroidDeckTheme { SheetChips(listOf("First", "Second"), selected.intValue) { selected.intValue = it } } } + verify("First", "Second") + } + + @Test fun segmentedTabsHaveOneTabRoleAndAnnounceTheirGroup() { + val selected = mutableIntStateOf(0) + compose.setContent { DroidDeckTheme { SegmentedTabs(listOf(0 to "First", 1 to "Second"), selected.intValue) { selected.intValue = it } } } + verify("First", "Second") + } + + @Test fun sideRailExposesSelectionEvenWhenOnlyIconsAreVisible() { + val selected = mutableStateOf("steam") + Hops.railPreview = null + compose.setContent { + DroidDeckTheme { + SideRail(FrontEndState( + installed = "r9", ready = true, available = null, busy = false, stage = "", percent = -1, + desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "", + romsDir = null, logsEnabled = false, steamGames = emptyList(), emulators = emptyList(), running = null, + ), selected.value, { selected.value = it }, {}, actions, Modifier.size(300.dp, 600.dp)) + } + } + compose.mainClock.advanceTimeBy(1_000) + val steam = compose.onNodeWithTag("rail-steam") + val games = compose.onNodeWithTag("rail-games") + assertTab(steam, true) + assertTab(games, false) + games.performClick() + compose.mainClock.advanceTimeBy(1_000) + assertTab(steam, false) + assertTab(games, true) + assertGroup() + } + + private fun verify(first: String, second: String) { + compose.mainClock.advanceTimeBy(1_000) + val a = compose.onNodeWithText(first) + val b = compose.onNodeWithText(second) + assertTab(a, true) + assertTab(b, false) + b.performClick() + compose.mainClock.advanceTimeBy(1_000) + assertTab(a, false) + assertTab(b, true) + assertGroup() + } + + private fun assertTab(node: SemanticsNodeInteraction, selected: Boolean) { + node.assert(SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.Tab)).assertHasClickAction() + if (selected) node.assertIsSelected() else node.assertIsNotSelected() + } + + private fun assertGroup() { + compose.onAllNodes(SemanticsMatcher.keyIsDefined(SemanticsProperties.SelectableGroup)).assertCountEquals(1) + } + + private val actions = FrontEndActions( + onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, + onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, + onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, + onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, + onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, + ) +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/ThemeColorsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/ThemeColorsTest.kt new file mode 100644 index 0000000000..b6f4de2044 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/ThemeColorsTest.kt @@ -0,0 +1,135 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.luminance +import androidx.compose.ui.graphics.toArgb +import com.droiddeck.launcher.session.SessionPrefs +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class ThemeColorsTest { + private val app get() = RuntimeEnvironment.getApplication() + + @Before fun clear() { + app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + } + + private fun near(expected: Int, actual: Int) { + for (shift in listOf(16, 8, 0)) assertTrue("${ThemeColors.hex(expected)} vs ${ThemeColors.hex(actual)}", Math.abs((expected shr shift and 0xFF) - (actual shr shift and 0xFF)) <= 1) + } + + @Test fun hueSaturationAndBrightnessComeBackAsTheSameColour() { + for (argb in listOf(0xFF8B5CF6.toInt(), 0xFF22D3EE.toInt(), 0xFFFF0000.toInt(), 0xFF336699.toInt(), 0xFF808080.toInt(), 0xFF000000.toInt(), 0xFFFFFFFF.toInt())) { + val hsv = ThemeColors.toHsv(argb) + near(argb, ThemeColors.fromHsv(hsv.h, hsv.s, hsv.v)) + } + } + + @Test fun hexIsReadWithOrWithoutTheHashAndInShortForm() { + assertEquals(0xFF8B5CF6.toInt(), ThemeColors.parseHex("#8B5CF6")) + assertEquals(0xFF8B5CF6.toInt(), ThemeColors.parseHex("8b5cf6")) + assertEquals(0xFFFF00AA.toInt(), ThemeColors.parseHex(" #f0a ")) + assertEquals("#8B5CF6", ThemeColors.hex(0xFF8B5CF6.toInt())) + for (bad in listOf("", "#", "#12", "#1234", "#1234567", "zzzzzz", "#12345g")) assertNull(bad, ThemeColors.parseHex(bad)) + } + + @Test fun aTooDarkColourIsLiftedAndABrightOneIsLeftAlone() { + val dark = ThemeColors.readable(0xFF050505.toInt()) + assertTrue(Color(dark).luminance() >= 0.10f) + assertEquals(0xFF8B5CF6.toInt(), ThemeColors.readable(0xFF8B5CF6.toInt())) + } + + @Test fun aDeepBlueThatBrightnessAloneCannotLiftIsMadePaler() { + assertTrue(Color(ThemeColors.readable(0xFF0000FF.toInt())).luminance() >= 0.10f) + assertTrue(Color(ThemeColors.readable(0xFF000000.toInt())).luminance() >= 0.10f) + } + + @Test fun theTextColourSuitsTheWorseOfTheTwoGradientColours() { + assertEquals(Color(0xFF03111F), ThemeColors.inkFor(0xFFFFEB3B.toInt(), 0xFF3B4FA8.toInt())) + assertEquals(Color.White, ThemeColors.inkFor(0xFF3B4FA8.toInt(), 0xFF5B2FA8.toInt())) + assertEquals(Color(0xFF03111F), ThemeColors.inkFor(0xFFFFFFFF.toInt(), 0xFFFFEB3B.toInt())) + } + + private fun contrast(a: Color, b: Color) = (maxOf(a.luminance(), b.luminance()) + 0.05f) / (minOf(a.luminance(), b.luminance()) + 0.05f) + + @Test fun buttonTextIsReadableOnBothGradientColoursForAnyPair() { + val picks = listOf(0xFFFFEB3B, 0xFF1E3A8A, 0xFF0000FF, 0xFFFF0000, 0xFF00FF00, 0xFF808080, 0xFFFFFFFF, 0xFF000000, 0xFF8B5CF6, 0xFF22D3EE, 0xFFFF5722, 0xFF3F51B5) + for (a in picks) for (b in picks) { + val p = ThemeColors.palette(a.toInt(), b.toInt(), 0, 0) + val first = p.primary.toArgb() + val second = p.primary2.toArgb() + for (step in 0..100) { + val fraction = step / 100f + val color = Color( + 0xFF000000.toInt() or + (channel(first, 16, second, fraction) shl 16) or + (channel(first, 8, second, fraction) shl 8) or + channel(first, 0, second, fraction), + ) + assertTrue( + "${ThemeColors.hex(first)} ${ThemeColors.hex(second)} at $fraction", + contrast(p.onPrimary, color) >= 4.5f, + ) + } + } + } + + private fun channel(first: Int, shift: Int, second: Int, fraction: Float): Int { + val start = first shr shift and 0xFF + val end = second shr shift and 0xFF + return (start + (end - start) * fraction).toInt().coerceIn(0, 255) + } + + @Test fun onlyTheStopThatFailsIsNudged() { + val p = ThemeColors.palette(0xFFFFEB3B.toInt(), 0xFF1E3A8A.toInt(), 0, 0) + assertEquals(Color(0xFFFFEB3B), p.primary) + assertTrue(p.primary2 != Color(0xFF1E3A8A)) + assertEquals(Color(0xFF03111F), p.onPrimary) + } + + @Test fun thePaletteKeepsTheTwoColoursAndStaysDarkAndReadable() { + val p = ThemeColors.palette(0xFF8B5CF6.toInt(), 0xFF22D3EE.toInt(), 0, 0) + assertEquals(p.primary, p.signal) + assertEquals(Color(0xFF22D3EE), p.primary2) + assertTrue(contrast(p.onPrimary, p.primary) >= 4.5f) + assertTrue(contrast(p.onPrimary, p.primary2) >= 4.5f) + assertTrue(p.background.luminance() < p.surface.luminance()) + assertTrue(p.surface.luminance() < p.surfaceVariant.luminance()) + assertTrue(p.background.luminance() < 0.02f) + assertTrue(p.onBackground.luminance() > 0.8f) + assertEquals(Color(0xFF03111F), ThemeColors.palette(0xFFFFEB3B.toInt(), 0xFFFFFFFF.toInt(), 0, 0).onPrimary) + assertEquals(Color.White, ThemeColors.palette(0xFF1E40AF.toInt(), 0xFF1D4ED8.toInt(), 0, 0).onPrimary) + } + + @Test fun aGreyPrimaryGivesGreyNeutrals() { + val p = ThemeColors.palette(0xFFB0B0B0.toInt(), 0xFFFFFFFF.toInt(), 0, 0) + assertEquals(p.background.red, p.background.blue, 0.002f) + } + + @Test fun theGradientThemeFollowsTheSavedColoursAndComesBackAfterARestart() { + Themes.setGradient(app, 0xFFFF5722.toInt(), 0xFF3F51B5.toInt()) + val live = Themes.byId(Themes.GRADIENT) + assertEquals(0xFFFF5722.toInt() to 0xFF3F51B5.toInt(), SessionPrefs.gradientColors(app)) + assertTrue(contrast(live.onPrimary, live.primary) >= 4.5f) + assertTrue(contrast(live.onPrimary, live.primary2) >= 4.5f) + SessionPrefs.setTheme(app, Themes.GRADIENT) + Themes.setGradient(app, Themes.DEFAULT_PRIMARY, Themes.DEFAULT_SECONDARY) + SessionPrefs.setGradientColors(app, 0xFF00FF00.toInt(), 0xFF0000FF.toInt()) + assertEquals(Color(0xFF00FF00), Themes.current(app).primary) + } + + @Test fun theGradientIsAChoiceInTheThemeList() { + assertTrue(Themes.all.any { it.id == Themes.GRADIENT }) + assertEquals(Themes.GRAPHITE, Themes.byId("nonsense").id) + } +} diff --git a/docs/adreno-850-experimental.md b/docs/adreno-850-experimental.md new file mode 100644 index 0000000000..28c1dd3f67 --- /dev/null +++ b/docs/adreno-850-experimental.md @@ -0,0 +1,80 @@ +# Experimental Adreno 850 detection and driver imports + +Reports [#342](https://github.com/Droid-Deck/DroidDeck/issues/342) and +[#723](https://github.com/Droid-Deck/DroidDeck/issues/723) describe Turnip failing +on Adreno 850, including an SM8975 / Adreno850v2 device reporting +`VK_ERROR_INCOMPATIBLE_DRIVER`. These reports motivate the detection changes; +they are not proof that the application's existing Turnip builds support A850. + +## Detection + +The application parses a GPU model only from an Adreno device name. The raw +KGSL `gpu_chipid` is recorded separately in device diagnostics: a decimal or +hexadecimal chip ID is not an Adreno model number. + +Detection prefers the KGSL name, then an already cached Vulkan device name, +then a platform fallback. An explicit `SM8975` or `QTI SM8975` SoC identifies +Adreno 850 when neither device name is available, including when the board +property still uses an older platform name. Driver auto selection uses the +same detection, with existing external-driver and Quest overrides retained. +This does not start a new Vulkan query during driver selection. + +A850 is labelled experimental. The SM8975 platform identity retains that +classification even when the selected driver reports Adreno 840; the displayed +model still follows the KGSL/Vulkan name. Identifying the hardware does not add native +A850 support to Turnip or prove that Steam and games will run. + +## Optional community driver bundle + +The community attachments uploaded to #342 on 2026-10-12 contain experimental +Android display and Linux game drivers. Their metadata describes a binary +patch that treats A850 as A840 and reuses some Adreno X2 entries. These are +not native A850 drivers; they may fail to start, hang, or render incorrectly, +and have not been validated across A850 revisions. + +Download the original attachments separately: + +| Platform | Original attachment | SHA-256 | +| --- | --- | --- | +| Android | [AdrenoTools-A850-experimental.zip](https://github.com/user-attachments/files/33319268/AdrenoTools-A850-experimental.zip) | `0cf849d068c875f6c469380ca1f74da1f757575bce53d4ef9c1f6d38677cbe8b` | +| Linux | [A850-experimental.zip](https://github.com/user-attachments/files/33319267/A850-experimental.zip) | `40fc59506620001531b9bdd1c9152e104c6fb1f4c07773c4743b9d70deb87eec` | + +Prepare a bundle accepted by DroidDeck's existing DriverBundle importer: + +```sh +mkdir -p build/a850-experimental +python3 tools/prepare_a850_driver_bundle.py \ + --android /absolute/path/AdrenoTools-A850-experimental.zip \ + --linux /absolute/path/A850-experimental.zip \ + --output build/a850-experimental/A850-community-experimental.zip +``` + +The tool accepts only the pinned originals, validates their ZIP entries, +metadata and ELF platform, and preserves the original files byte for byte. +It does not download, execute or rebuild drivers. Neither binary is included +in the source tree or installed automatically by these changes. + +To try the bundle, stop the session and wait for any automatic driver check +or download to finish. Note the existing driver selections, then use +**Components → GPU drivers → Mix and match → Import .zip**. This is a GPU +driver bundle, not a Decky plugin ZIP. Confirm that both the Android display +and Linux game drivers are selected, then fully exit and reopen the app. +Keep **Session → Performance → Session repair → Turnip: sysmem rendering** +enabled as advised by the original Linux driver metadata. + +Test entering Steam separately from game rendering. If it fails, restore the +previous drivers and restart the app. Preserve the **Share logs** ZIP, +including `device.txt`, `session.log`, the exact chip ID and Android version. + +## Validation + +```sh +python3 -m unittest discover -s tools/tests -p test_a850_driver_bundle.py -v +./gradlew -PskipRust=true :app:testDebugUnitTest --tests 'com.droiddeck.launcher.gpu.*' +``` + +The tests cover detection priority, chip-ID rejection, SoC normalization, +experimental status, driver-generation selection and bundle integrity. They +do not replace Vulkan, Steam or game testing on the target phone. A user +confirmed that importing the experimental bundle succeeded; target-device +Steam and game compatibility remain unverified. diff --git a/docs/development/themes.md b/docs/development/themes.md new file mode 100644 index 0000000000..b7f1a01eb3 --- /dev/null +++ b/docs/development/themes.md @@ -0,0 +1,25 @@ +# Themes + +A theme is a `Palette` (`ui/Theme.kt`): a dark background scale (`background`, `surface`, +`surfaceVariant`, `line`, `line2`), two text colours, and the accent: `primary` / `signal` +(flat accent, also Material's primary), `primary2` (the darker or second accent) and +`onPrimary`. `PrimaryButton` and the launch flood already draw a gradient from `primary` to +`primary2`. The choice is stored as an id (`SessionPrefs.theme`) and picked in Setup › Launcher. + +## Gradient theme + +`Themes.GRADIENT` is the one theme whose colours the person picks: a primary and a secondary, +kept in `SessionPrefs.gradientColors` and in `Themes.gradientColors`, a Compose state, so a change +restyles the whole app at once. `App.onCreate` loads the saved colours; code outside a composition +uses `Themes.current(context)`. + +`ThemeColors.palette` builds the full palette from the two colours: primary becomes +`primary` / `signal`, secondary becomes `primary2`, the background scale is a dark neutral tinted with +the primary's hue (plain grey for a grey primary), and `onPrimary` is dark or white by the +luminance of the pair. A colour too dark to show on the dark background is lifted +(`ThemeColors.readable`) rather than refused. + +Setup shows Primary and Secondary under the theme when Gradient is chosen, each a small colour +square. It opens `ColorPickerDialog`: a wheel (hue and saturation, touch), hue / saturation / +brightness sliders (they work with a controller) and a hex box, with the old and new colour side by +side. OK applies it. diff --git a/docs/third-party/viture-v2/LICENSE b/docs/third-party/viture-v2/LICENSE new file mode 100644 index 0000000000..9c1d9de29a --- /dev/null +++ b/docs/third-party/viture-v2/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Holger Bartnick + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/docs/third-party/viture-v2/README.md b/docs/third-party/viture-v2/README.md new file mode 100644 index 0000000000..253b3b46f0 --- /dev/null +++ b/docs/third-party/viture-v2/README.md @@ -0,0 +1,47 @@ +# VITURE protocol V2 attribution and scope + +The frame builder, parser, pose/raw layouts, and commands in +`VitureV2Protocol.kt` are adapted from [elasticjava/viture-v2](https://github.com/elasticjava/viture-v2) +at commit `ece8c30485f7d357fefa362ae74f3eabac9b3899` (MIT). +Copyright (c) 2026 Holger Bartnick. The full license is in `LICENSE` here. + +Sources used are upstream `PROTOCOL.md`, `src/lib.rs`, and `src/xr.rs`. +Upstream developed and measured its driver on VITURE Pro 2 XR `35ca:1301`. +Its research used captures of the proprietary SDK's USB traffic and logging; +the resulting implementation communicates directly over USB without that SDK. +This is an SDK-free implementation, not a claim of SDK-independent protocol research. +Our earlier local proprietary SDK trace was not used for this adaptation. + +The Android transport and application integration are implemented in Kotlin. +Building this path requires no Rust toolchain, vendor SDK, vendor binary, +developer account, private download, or repository secret. It uses Android's +USB host permission and `UsbRequest` APIs. To explicitly build without the +optional vendor driver, pass the Gradle property `-PvitureSdkDir=`. + +The application enables this experimental transport only for `35ca:1301`. +It requires valid pose samples before advertising 3DoF, uses the upstream +120 Hz pose mode, and treats the device timestamp as an uninterpreted counter. +Delivered timestamps use host `System.nanoTime()` receipt times. Bootstrap and +resume reject samples collected before the enable write completes. This host-time +cutoff does not establish when hardware produced a sample or purge device/kernel +buffers. The pose +basis conversion follows upstream's Y-up rendering convention. Hardware captures +verify changing, normalized poses during head motion; the relative rotation mapping +is unit-tested. The user also reported a successful Pro 2 game test; see the +validation notes for the scope of that report. + +Raw gyro and accelerometer packets can be decoded with their complete payload +preserved, but raw data is not fused or used by the application. Upstream reports +that enabling pose and raw streams together can ACK successfully while sending +no samples, so the application requests pose alone. Accelerometer values remain +in g; gyroscope values are in radians/second according to upstream. + +Brightness, volume, and display queries are supported. Setters, display switching, +6DoF, cameras, and hand tracking are not implemented by this path. Upstream's +README/protocol document and source disagree about setter coverage; this +adaptation does not use those setters without device validation. + +The standalone `tools/viture/viture-v2-probe` captures descriptors, commands, +replies, and pose/raw packets for device compatibility testing. Its provenance +and license are included beside its source. Pro 2 hardware checks and their +limitations are recorded in [VALIDATION.md](VALIDATION.md). diff --git a/docs/third-party/viture-v2/VALIDATION.md b/docs/third-party/viture-v2/VALIDATION.md new file mode 100644 index 0000000000..8bdbf2bff4 --- /dev/null +++ b/docs/third-party/viture-v2/VALIDATION.md @@ -0,0 +1,102 @@ +# Pro 2 direct USB validation + +These tests used a Samsung Galaxy Z Fold7 (SM-F976U), Android 17, with glasses +connected to the phone and wireless ADB used for installation and log collection. +The tested Pro 2 identifies as `35ca:1301`, with interface 0 exposing 64-byte +interrupt IN `0x81` and interrupt OUT `0x01`. Its firmware query returned +`30.0.00.001_20260714`. Results apply to this device and firmware. + +## Protocol probe + +The SDK-free Java probe in `tools/viture/viture-v2-probe` uses the attributed MIT +protocol. Every run queried firmware, enabled one stream, and sent stream-off at +completion. Each Pro 2 run received a successful firmware response and successful +start/stop acknowledgments. All three had zero malformed frames or samples. + +| Run | Valid samples | Measured rate | Observation | +| --- | ---: | ---: | --- | +| Pose, initial 15-second window | 1,762 | 120.67 Hz | Normalized quaternions; components changed | +| Pose, 30-second motion window | 3,571 | 120.63 Hz | User turned, looked up/down, and tilted; all components varied | +| Raw, separate 15-second window | 1,471 | 100.77 Hz | Finite gyro and accelerometer values; acceleration magnitude 0.882–1.129 g | + +Rates use host receipt time between the first and last samples. Query/setup time +reduces the sampling interval within each window. Although both stream requests +specified the upstream 120 Hz setting, the raw stream delivered approximately +101 Hz. Device counters are retained without assigning time units. Pose quaternion +norms were within 0.00000007 of one. These measurements do not establish accuracy, +drift, physical axis signs in a rendered scene, or 6DoF. + +Raw gyro/accelerometer decoding is available for future work. The application uses +only the device's pose stream. Combined pose/raw streaming is deliberately excluded +because upstream observed acknowledgments without subsequent samples in that mode. + +## Reproducing the checks + +Build the application with `-PvitureSdkDir=` to explicitly exclude the optional +vendor SDK. No vendor SDK download, vendor account, binary upload, or repository +secret is required for Pro 2. See each tool's README/provenance document for Android +SDK/JDK requirements, build commands, USB permission, and log collection. + +The protocol probe is separate from the application driver. The +`tools/viture/viture-v2-driver-check` harness packages the actual compiled +`VitureV2Link`, `VitureV2Protocol`, and `GlassesLink` classes and records their hashes. +It verifies readiness from poses and a stop/restart/stop/close sequence. + +On the same Pro 2, the final production-driver check **passed**: 1,446 poses in the +12-second resumed capture at 120.65 Hz, plus three bootstrap poses. It reported one +ready callback, two tracking-on and two tracking-off callbacks, zero errors and +zero bad frames. Both 500 ms pause windows delivered zero further poses. After +close, readiness and tracking were both false. The complete sequence took 13.03 s. +This validates the production USB driver; it does not by itself exercise the full +DroidDeck UI or an in-game head-tracking session. + +All 115 selected host-side tests passed. They cover wire framing/checksums, +bounded parsing, pose and raw layouts, +invalid samples, readiness without trusting ACKs, host-receipt cutoffs and +duplicate/backward device-tick rejection, +stop/restart behavior, transport failures, relative coordinate conversion, exact +USB model routing, consumer removal before the first restarted pose, and UI hiding +of unsupported hardware/display controls. + +## Full application check + +The complete debug APK built successfully with `:app:assembleDebug -PvitureSdkDir=` +and passed the repository's runtime-input verification and APK signature checks. +The APK contains the upstream MIT license and contains none of `libglasses.so`, +`libcarina_vio.so`, `libcloud_protocol.so`, or `libdroiddeck_viture.so`. + +Installed as `com.droiddeck.launcher.xr`, version 0.5.0, on the same phone, it +recognized Pro 2 and exposed `supportsScreen3dof=true` after USB permission and +valid bootstrap samples. A five-second sample through DroidDeck's own `glasses` +agent endpoint returned **595 poses (118.98 Hz including startup)**, with quaternion +norms within 0.00000006 of one and zero bad frames. Tracking was false before the +sample, true during it, and false afterward; the connection remained ready with +no control error. This checks application integration and consumer-driven streaming, +not an in-game rendering or SteamVR session. + +Tested APK SHA-256: +`f5a2484ea1708a143cb94a96e084188cb0d2b122154a2645d3127c66f6d04f21`. + +## User game test + +After installing the tested build, the user reported that the Pro 2 game test +passed. This adds user-reported in-game validation to the automated USB and +application checks above. The game title, test duration, and separate recentering +or SteamVR checks were not recorded. + +## Local capture fingerprints + +Full motion logs are local diagnostic artifacts, not required build inputs. These +SHA-256 values identify the captures behind the table above: + +| Capture | SHA-256 | +| --- | --- | +| `pro2-pose-initial.jsonl` | `beb09072d8d7ce2b1378c41992b88787e0b09f3ab3ea330a413b3ef9e9f5b762` | +| `pro2-pose-motion.jsonl` | `d72f3bbd6564061e9bf4e06fec7f4c6dcdbfabeee626a99a7bff279b416ccc61` | +| `pro2-raw.jsonl` | `944ac2fe30c7b1a817bc4d3281ead620000be32aa2dbd96e6b104cf4d7063091` | +| `pro2-production-driver-final.jsonl` | `0f1c1073963a7c3052bf8bdbcb39e3ef8ec332367ab1a3e39b622d36fcd06db2` | +| `pro2-full-app.json` | `3e48d9c3e8a230ec84e09bb51395b8566618406abb93937b8e2b69c40b4854c5` | + +The provenance in [README.md](README.md) applies to all these checks: the upstream +MIT project used SDK traffic captures in its research. This adaptation contains +and loads no vendor SDK; it does not claim independent protocol discovery. diff --git a/tools/desktop-kde/README.md b/tools/desktop-kde/README.md index ced96147e1..b76457f60f 100644 --- a/tools/desktop-kde/README.md +++ b/tools/desktop-kde/README.md @@ -22,9 +22,11 @@ through `kwin_wayland_wrapper`. KWin composites in software (QPainter) - the Adr DRM device - so games and emulators from the menu go through `droiddeck-gpu`, and Steam goes back to the app as a Steam session. -`build-kwin.sh` builds KWin 6.7.5's Wayland executable and library on a native ARM64 runner, using a disposable -Arch Linux ARM chroot with every build package signature-checked. The KDE source tarball is pinned -by SHA-256 (the same digest in Arch's KWin PKGBUILD); `patches/0001-respect-nested-desktop-scale.patch` +`kwin.env` pins the KWin version shared by the build and packaging jobs. `build-kwin.sh` builds that version's +Wayland executable and library on a native ARM64 runner, using a disposable +Arch Linux ARM chroot with every build package signature-checked. It matches the current KWin package +in Arch Linux ARM even when that repository trails KDE's latest release. The source tarball is pinned +by SHA-256 from KDE's official source inventory; `patches/0001-respect-nested-desktop-scale.patch` lets Display Settings control the inner desktop scale independently of the outer window size. It keeps layer sizes, pointer/touch coordinates and the cursor in the same physical pixels. The behavior is enabled only with `DROIDDECK_NESTED_SCALE`, which the desktop script supplies. @@ -32,7 +34,7 @@ The behavior is enabled only with `DROIDDECK_NESTED_SCALE`, which the desktop sc The desktop workflow replaces the same-version `kwin_wayland` executable and `libkwin.so`; the rest comes from the signature-checked Arch packages. `desktop-kde.kwin.txt` records the source, patch, executable, library and build package hashes. Corresponding source is -https://download.kde.org/stable/plasma/6.7.5/kwin-6.7.5.tar.xz plus the patch in this repository. +https://download.kde.org/stable/plasma/6.8.0/kwin-6.8.0.tar.xz plus the patch in this repository. The inventories use `.gzip` rather than `.gz`: Android's asset packer expands `.gz` and strips its suffix. The shared local/CI runtime payload check verifies the exact APK names and bytes. diff --git a/tools/desktop-kde/build-kwin.sh b/tools/desktop-kde/build-kwin.sh index ae6ac49430..c740d484ab 100644 --- a/tools/desktop-kde/build-kwin.sh +++ b/tools/desktop-kde/build-kwin.sh @@ -3,8 +3,9 @@ set -euo pipefail out=$(realpath -m "${1:?out dir}") here=$(cd "$(dirname "$0")" && pwd) [ "$(uname -m)" = aarch64 ] || { echo 'KWin needs a native aarch64 runner' >&2; exit 1; } -version=6.7.5 -source_sha=6baa910b732d93c48c90f9c1cc685cc93d0b8de0cdf138c24192c045bc3a48e2 +source "$here/kwin.env" +version=$DESKTOP_KWIN_VERSION +source_sha=4bfaf31e29a8f9fdf231dc3bbb9b09b0ce07cae9fee7a01cfc86425ece796258 mirror=https://fl.us.mirror.archlinuxarm.org/aarch64 builder=68B3537F39A313B3E574D06777193F152BDBE6A6 work=$(mktemp -d) @@ -18,7 +19,11 @@ for repo in core extra alarm; do done touch "$work/runtime.txt" python3 "$here/closure.py" "$work/db" "$work/runtime.txt" "$here/kwin-build-seeds.txt" > "$work/packages.txt" -grep -Eq '^extra/kwin-6\.7\.5-[0-9]+-aarch64\.pkg\.tar\.' "$work/packages.txt" +kwin_package=$(awk '$1 ~ /^extra\/kwin-.*-aarch64\.pkg\.tar\./ {print $1}' "$work/packages.txt") +case $kwin_package in + "extra/kwin-$version"-[0-9]*-aarch64.pkg.tar.*) ;; + *) echo "KWin package $kwin_package does not match source KWin $version" >&2; exit 1 ;; +esac export work mirror builder here download() { local entry=$1 sum=$2 file=${1#*/} diff --git a/tools/desktop-kde/build.sh b/tools/desktop-kde/build.sh index 80bd41e11a..b434e81bc5 100755 --- a/tools/desktop-kde/build.sh +++ b/tools/desktop-kde/build.sh @@ -2,6 +2,7 @@ set -euo pipefail out=${1:?out dir} here=$(cd "$(dirname "$0")" && pwd) +source "$here/kwin.env" mirror=${ALARM_MIRROR:-https://fl.us.mirror.archlinuxarm.org/aarch64} case $mirror in https://*) ;; *) echo "ALARM_MIRROR must be https" >&2; exit 1 ;; esac builder=68B3537F39A313B3E574D06777193F152BDBE6A6 @@ -36,8 +37,13 @@ done < "$work/pkglist.txt" cp -a "$here/overlay/." "$work/root/" if [ -n "${KDE_KWIN_OVERRIDE:-}" ]; then + kwin_package=$(awk '$1 ~ /^extra\/kwin-.*-aarch64\.pkg\.tar\./ {print $1}' "$work/pkglist.txt") + case $kwin_package in + "extra/kwin-$DESKTOP_KWIN_VERSION"-[0-9]*-aarch64.pkg.tar.*) ;; + *) echo "KWin package $kwin_package does not match the built KWin $DESKTOP_KWIN_VERSION" >&2; exit 1 ;; + esac install -m 755 "$KDE_KWIN_OVERRIDE/kwin_wayland" "$work/root/usr/bin/kwin_wayland" - install -m 755 "$KDE_KWIN_OVERRIDE/libkwin.so.6.7.5" "$work/root/usr/lib/libkwin.so.6.7.5" + install -m 755 "$KDE_KWIN_OVERRIDE/libkwin.so.$DESKTOP_KWIN_VERSION" "$work/root/usr/lib/libkwin.so.$DESKTOP_KWIN_VERSION" fi if [ -d "$work/root/usr/share/locale" ]; then diff --git a/tools/desktop-kde/kwin.env b/tools/desktop-kde/kwin.env new file mode 100644 index 0000000000..d6ef0cee96 --- /dev/null +++ b/tools/desktop-kde/kwin.env @@ -0,0 +1 @@ +DESKTOP_KWIN_VERSION=6.8.0 diff --git a/tools/desktop-kde/overlay/usr/share/licenses/droiddeck-desktop/NOTICE b/tools/desktop-kde/overlay/usr/share/licenses/droiddeck-desktop/NOTICE index 23bc15cc14..a806a082e6 100644 --- a/tools/desktop-kde/overlay/usr/share/licenses/droiddeck-desktop/NOTICE +++ b/tools/desktop-kde/overlay/usr/share/licenses/droiddeck-desktop/NOTICE @@ -8,8 +8,8 @@ Third-party files in DroidDeck's KDE desktop package (tools/desktop-kde/overlay) - steam.svg: Papirus icon theme (https://github.com/PapirusDevelopmentTeam/papirus-icon-theme), GPL-3.0. -- kwin_wayland: KWin 6.7.5, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch. - Corresponding source: https://download.kde.org/stable/plasma/6.7.5/kwin-6.7.5.tar.xz and +- kwin_wayland: KWin 6.8.0, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch. + Corresponding source: https://download.kde.org/stable/plasma/6.8.0/kwin-6.8.0.tar.xz and https://github.com/Droid-Deck/DroidDeck/tree/fix/kde-desktop-followups/tools/desktop-kde/patches (the source and patch hashes are recorded in desktop-kde.kwin.txt beside the package). diff --git a/tools/desktop-kde/patches/0001-respect-nested-desktop-scale.patch b/tools/desktop-kde/patches/0001-respect-nested-desktop-scale.patch index 7c8767ff81..8ad3a5238a 100644 --- a/tools/desktop-kde/patches/0001-respect-nested-desktop-scale.patch +++ b/tools/desktop-kde/patches/0001-respect-nested-desktop-scale.patch @@ -1,78 +1,27 @@ ---- a/src/backends/wayland/wayland_output.cpp -+++ b/src/backends/wayland/wayland_output.cpp -@@ -294,6 +294,11 @@ - } - } - -+qreal WaylandOutput::presentationScale() const -+{ -+ return qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE") ? m_pendingScale : scale(); -+} -+ - bool WaylandOutput::present(const QList &layersToUpdate, const std::shared_ptr &frame) - { - auto cursorLayers = layersToUpdate | std::views::filter([](OutputLayer *layer) { -@@ -312,7 +317,7 @@ - m_surface->attachBuffer(buffer); - m_mapped = true; - } -- m_viewport->setDestination(QSize(std::round(modeSize().width() / scale()), std::round(modeSize().height() / scale()))); -+ m_viewport->setDestination(QSize(std::round(modeSize().width() / presentationScale()), std::round(modeSize().height() / presentationScale()))); - m_surface->setScale(1); - // commit the subsurfaces before the main surface - for (OutputLayer *layer : layersToUpdate) { -@@ -375,9 +380,11 @@ - next.enabled = props->enabled.value_or(m_state.enabled); - next.transform = props->transform.value_or(m_state.transform); - next.position = props->pos.value_or(m_state.position); -- // intentionally ignored, as it would get overwritten -- // with the fractional scale protocol anyways -- // next.scale = props->scale.value_or(m_state.scale); -+ -+ if (qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) { -+ next.scale = props->scale.value_or(m_state.scale); -+ next.scaleSetting = props->scaleSetting.value_or(m_state.scaleSetting); -+ } - next.desiredMode = props->desiredMode.value_or(m_state.desiredMode); - next.uuid = props->uuid.value_or(m_state.uuid); - next.replicationSource = props->replicationSource.value_or(m_state.replicationSource); -@@ -466,7 +473,9 @@ - State next = m_state; - next.modes = {mode}; - next.currentMode = mode; -- next.scale = m_pendingScale; -+ if (!qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) { -+ next.scale = m_pendingScale; -+ } - setState(next); - - Q_EMIT m_backend->outputsQueried(); ---- a/src/backends/wayland/wayland_output.h -+++ b/src/backends/wayland/wayland_output.h -@@ -93,6 +93,8 @@ - - void init(const QSize &pixelSize, qreal scale, bool fullscreen); - -+ -+ qreal presentationScale() const; - bool isReady() const; - KWayland::Client::Surface *surface() const; - WaylandCursor *cursor() const; +diff --git a/src/backends/wayland/wayland_backend.cpp b/src/backends/wayland/wayland_backend.cpp +index f43f03d..211ef09 100644 --- a/src/backends/wayland/wayland_backend.cpp +++ b/src/backends/wayland/wayland_backend.cpp -@@ -107,8 +107,9 @@ +@@ -106,16 +106,8 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::Pointer *pointer, Wayla WaylandOutput *output = m_seat->backend()->findOutput(m_pointer->enteredSurface()); Q_ASSERT(output); const auto subsurface = m_seat->backend()->findSubSurface(m_pointer->enteredSurface()); -- const QPointF absolutePos = output->position() + relativeToSurface -- + (subsurface ? subsurface->position() : QPoint()); -+ const QPointF absolutePos = output->position() -+ + (relativeToSurface + (subsurface ? subsurface->position() : QPoint())) -+ * output->presentationScale() / output->scale(); +- // A position in the host window is in the coordinates the panel is driven in, while +- // the compositor works in the picture as the user sees it. On a rotated display those +- // are not the same, so the position has to be turned back. +- const QPointF inPanel = relativeToSurface + (subsurface ? subsurface->position() : QPoint()); +- // Exactly the size the surface is given in WaylandOutput::present(), rounding and all - +- // turning a position needs the bounds it was expressed in, and being off by the +- // rounding here shifts the pointer by a little more the further it travels. +- const QSizeF panelSize = QSize(std::round(output->modeSize().width() / output->scale()), +- std::round(output->modeSize().height() / output->scale())); +- const QPointF absolutePos = output->position() + output->transform().inverted().map(inPanel, panelSize); ++ const QPointF hostPosition = relativeToSurface + (subsurface ? subsurface->position() : QPoint()); ++ const QPointF absolutePos = output->mapToOutput(hostPosition); Q_EMIT pointerMotionAbsolute(absolutePos, std::chrono::milliseconds(time), this); }); connect(pointer, &Pointer::buttonStateChanged, this, [this](quint32 serial, quint32 time, quint32 button, Pointer::ButtonState nativeState) { -@@ -182,7 +183,11 @@ +@@ -189,7 +181,11 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::RelativePointer *relati , m_relativePointer(relativePointer) { connect(relativePointer, &RelativePointer::relativeMotion, this, [this](const QSizeF &delta, const QSizeF &deltaNonAccelerated, quint64 timestamp) { @@ -84,16 +33,17 @@ + Q_EMIT pointerMotion(sizeToPoint(delta) * factor, sizeToPoint(deltaNonAccelerated) * factor, std::chrono::microseconds(timestamp), this); }); } - -@@ -199,13 +204,19 @@ + +@@ -206,13 +202,21 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::Touch *touch, WaylandSe connect(touch, &Touch::sequenceStarted, this, [this](TouchPoint *tp) { auto o = m_seat->backend()->findOutput(tp->surface()); Q_ASSERT(o); - const QPointF position = o->position() + tp->position(); + const auto subsurface = m_seat->backend()->findSubSurface(tp->surface()); -+ const QPointF position = o->position() -+ + (tp->position() + (subsurface ? subsurface->position() : QPoint())) -+ * o->presentationScale() / o->scale(); ++ const QPointF hostPosition = tp->position() + (subsurface ? subsurface->position() : QPoint()); ++ const QPointF position = qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE") ++ ? o->mapToOutput(hostPosition) ++ : o->position() + tp->position(); Q_EMIT touchDown(tp->id(), position, std::chrono::milliseconds(tp->time()), this); }); connect(touch, &Touch::pointAdded, this, [this](TouchPoint *tp) { @@ -101,27 +51,46 @@ Q_ASSERT(o); - const QPointF position = o->position() + tp->position(); + const auto subsurface = m_seat->backend()->findSubSurface(tp->surface()); -+ const QPointF position = o->position() -+ + (tp->position() + (subsurface ? subsurface->position() : QPoint())) -+ * o->presentationScale() / o->scale(); ++ const QPointF hostPosition = tp->position() + (subsurface ? subsurface->position() : QPoint()); ++ const QPointF position = qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE") ++ ? o->mapToOutput(hostPosition) ++ : o->position() + tp->position(); Q_EMIT touchDown(tp->id(), position, std::chrono::milliseconds(tp->time()), this); }); connect(touch, &Touch::pointRemoved, this, [this](TouchPoint *tp) { -@@ -214,7 +225,10 @@ +@@ -221,7 +225,11 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::Touch *touch, WaylandSe connect(touch, &Touch::pointMoved, this, [this](TouchPoint *tp) { auto o = m_seat->backend()->findOutput(tp->surface()); Q_ASSERT(o); - const QPointF position = o->position() + tp->position(); + const auto subsurface = m_seat->backend()->findSubSurface(tp->surface()); -+ const QPointF position = o->position() -+ + (tp->position() + (subsurface ? subsurface->position() : QPoint())) -+ * o->presentationScale() / o->scale(); ++ const QPointF hostPosition = tp->position() + (subsurface ? subsurface->position() : QPoint()); ++ const QPointF position = qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE") ++ ? o->mapToOutput(hostPosition) ++ : o->position() + tp->position(); Q_EMIT touchMotion(tp->id(), position, std::chrono::milliseconds(tp->time()), this); }); } +diff --git a/src/backends/wayland/wayland_egl_backend.cpp b/src/backends/wayland/wayland_egl_backend.cpp +index 0c03222..c587db5 100644 +--- a/src/backends/wayland/wayland_egl_backend.cpp ++++ b/src/backends/wayland/wayland_egl_backend.cpp +@@ -232,7 +232,9 @@ bool WaylandEglCursorLayer::endFrame(const Region &renderedDeviceRegion, const R + wl_buffer *buffer = m_backend->backend()->importBuffer(m_buffer->buffer()); + Q_ASSERT(buffer); + +- static_cast(m_output.get())->cursor()->update(buffer, m_buffer->buffer()->size() / m_output->scale(), (hotspot() / m_output->scale()).toPoint()); ++ auto output = static_cast(m_output.get()); ++ output->cursor()->update(buffer, m_buffer->buffer()->size() / output->presentationScale(), ++ (hotspot() / output->presentationScale()).toPoint()); + + EGLNativeFence releaseFence{m_backend->eglDisplayObject()}; + m_swapchain->release(m_buffer, releaseFence.takeFileDescriptor()); +diff --git a/src/backends/wayland/wayland_layer.cpp b/src/backends/wayland/wayland_layer.cpp +index 311be7f..f91a3fb 100644 --- a/src/backends/wayland/wayland_layer.cpp +++ b/src/backends/wayland/wayland_layer.cpp -@@ -95,7 +95,7 @@ +@@ -95,7 +95,7 @@ void WaylandLayer::commit(PresentationMode presentationMode) // this is a bit annoying, we need a new Wayland protocol // to do this properly with fractional scaling. Until we // have that, it may cause blurriness in some cases! @@ -130,29 +99,74 @@ if (m_viewport) { m_viewport->setSource(sourceRect()); m_viewport->setDestination(logicalTarget.size()); ---- a/src/backends/wayland/wayland_qpainter_backend.cpp -+++ b/src/backends/wayland/wayland_qpainter_backend.cpp -@@ -124,7 +124,9 @@ - wl_buffer *buffer = static_cast(m_output.get())->backend()->importBuffer(m_back->buffer()); - Q_ASSERT(buffer); - -- static_cast(m_output.get())->cursor()->update(buffer, m_back->buffer()->size() / m_output->scale(), hotspot().toPoint()); -+ auto output = static_cast(m_output.get()); -+ output->cursor()->update(buffer, m_back->buffer()->size() / output->presentationScale(), -+ (hotspot() * output->scale() / output->presentationScale()).toPoint()); - m_swapchain->release(m_back); - return true; +diff --git a/src/backends/wayland/wayland_output.cpp b/src/backends/wayland/wayland_output.cpp +index 1543058..a22d974 100644 +--- a/src/backends/wayland/wayland_output.cpp ++++ b/src/backends/wayland/wayland_output.cpp +@@ -314,7 +314,7 @@ std::expected WaylandOutput::present(const QListattachBuffer(buffer); + m_mapped = true; + } +- const Rect rect(QPoint(), QSize(std::round(modeSize().width() / scale()), std::round(modeSize().height() / scale()))); ++ const Rect rect(QPoint(), QSize(std::round(modeSize().width() / presentationScale()), std::round(modeSize().height() / presentationScale()))); + m_xdgShellSurface->setWindowGeometry(rect); + m_viewport->setDestination(rect.size()); + m_surface->setScale(1); +@@ -379,9 +379,10 @@ void WaylandOutput::applyChanges(const OutputConfiguration &config) + next.enabled = props->enabled.value_or(m_state.enabled); + next.transform = props->transform.value_or(m_state.transform); + next.position = props->pos.value_or(m_state.position); +- // intentionally ignored, as it would get overwritten +- // with the fractional scale protocol anyways +- // next.scale = props->scale.value_or(m_state.scale); ++ if (qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) { ++ next.scale = props->scale.value_or(m_state.scale); ++ next.scaleSetting = props->scaleSetting.value_or(m_state.scaleSetting); ++ } + next.desiredMode = props->desiredMode.value_or(m_state.desiredMode); + next.uuid = props->uuid.value_or(m_state.uuid); + next.replicationSource = props->replicationSource.value_or(m_state.replicationSource); +@@ -397,6 +398,19 @@ void WaylandOutput::applyChanges(const OutputConfiguration &config) + setState(next); } ---- a/src/backends/wayland/wayland_egl_backend.cpp -+++ b/src/backends/wayland/wayland_egl_backend.cpp -@@ -202,7 +202,9 @@ - wl_buffer *buffer = m_backend->backend()->importBuffer(m_buffer->buffer()); - Q_ASSERT(buffer); - -- static_cast(m_output.get())->cursor()->update(buffer, m_buffer->buffer()->size() / m_output->scale(), (hotspot() / m_output->scale()).toPoint()); -+ auto output = static_cast(m_output.get()); -+ output->cursor()->update(buffer, m_buffer->buffer()->size() / output->presentationScale(), -+ (hotspot() / output->presentationScale()).toPoint()); - - EGLNativeFence releaseFence{m_backend->eglDisplayObject()}; - m_swapchain->release(m_buffer, releaseFence.takeFileDescriptor()); + ++qreal WaylandOutput::presentationScale() const ++{ ++ return qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE") ? m_pendingScale : scale(); ++} ++ ++QPointF WaylandOutput::mapToOutput(const QPointF &hostPosition) const ++{ ++ const QPointF inPanel = hostPosition * presentationScale() / scale(); ++ const QSizeF panelSize = QSize(std::round(modeSize().width() / scale()), ++ std::round(modeSize().height() / scale())); ++ return position() + transform().inverted().map(inPanel, panelSize); ++} ++ + bool WaylandOutput::isReady() const + { + return m_ready; +@@ -472,7 +486,9 @@ void WaylandOutput::applyConfigure(const QSize &size, quint32 serial) + State next = m_state; + next.modes = {mode}; + next.currentMode = mode; +- next.scale = m_pendingScale; ++ if (!qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) { ++ next.scale = m_pendingScale; ++ } + setState(next); + + Q_EMIT m_backend->outputsQueried(); +diff --git a/src/backends/wayland/wayland_output.h b/src/backends/wayland/wayland_output.h +index dab061b..c019577 100644 +--- a/src/backends/wayland/wayland_output.h ++++ b/src/backends/wayland/wayland_output.h +@@ -92,6 +92,8 @@ public: + + void init(const QSize &pixelSize, qreal scale, bool fullscreen); + ++ qreal presentationScale() const; ++ QPointF mapToOutput(const QPointF &hostPosition) const; + bool isReady() const; + KWayland::Client::Surface *surface() const; + WaylandCursor *cursor() const; diff --git a/tools/device-smoke.sh b/tools/device-smoke.sh new file mode 100755 index 0000000000..bec8fed81b --- /dev/null +++ b/tools/device-smoke.sh @@ -0,0 +1,287 @@ +#!/usr/bin/env bash +# Smoke test of a DroidDeck build on a real device, over plain adb (no python, no root). +# +# What it does, in order, and restores afterwards: +# 1. prints the device (model, Android, kernel, page size, SoC); +# 2. installs --apk when given and launches the app; +# 3. checks that the app starts and that nothing in the crash buffer belongs to it; +# 4. changes the display density and the window size and checks the app keeps its process +# (and does not recreate the activity that is on top); +# 5. on a foldable cycles the device state (half-opened, and with --closed also closed) through +# `cmd device_state`, then puts the original state back; +# 6. reads the newest session folder of a debug build: first frame, last frame rate, the +# memory page size and the last process exits. +# +# Usage: tools/device-smoke.sh [--serial SERIAL] [--apk FILE] [--pkg PACKAGE] +# [--no-density] [--no-size] [--no-fold] [--closed] +# Exit status: 0 when no check failed, 1 when one did, 2 for a usage or device problem. +# +# Not a replacement for tools/droiddeck-scenario, which drives a game through the agent bridge; +# this covers what that does not: display changes and foldable states. +set -u +export MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*' + +pkg=com.droiddeck.launcher +serial=${ANDROID_SERIAL:-} +apk= +do_density=1 +do_size=1 +do_fold=1 +do_closed=0 +adb_bin=${ADB:-adb} + +while [ $# -gt 0 ]; do + case $1 in + --serial) [ $# -ge 2 ] || { echo "--serial needs a value" >&2; exit 2; }; serial=$2; shift ;; + --apk) [ $# -ge 2 ] || { echo "--apk needs a value" >&2; exit 2; }; apk=$2; shift ;; + --pkg) [ $# -ge 2 ] || { echo "--pkg needs a value" >&2; exit 2; }; pkg=$2; shift ;; + --no-density) do_density=0 ;; + --no-size) do_size=0 ;; + --no-fold) do_fold=0 ;; + --closed) do_closed=1 ;; + -h|--help) sed -n '2,22p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "unknown option: $1" >&2; exit 2 ;; + esac + shift +done + +adb_cmd=("$adb_bin") +[ -n "$serial" ] && adb_cmd+=(-s "$serial") +A() { + local out rc + out=$("${adb_cmd[@]}" "$@" 2>&1); rc=$? + [ -z "$out" ] || printf '%s\n' "$out" | tr -d '\r' + return $rc +} +sh_() { + local command= arg + for arg in "$@"; do command+="'${arg//\'/\'\\\'\'}' "; done + A shell "$command" +} + +pass=0 fail=0 skip=0 +ok() { echo " PASS $*"; pass=$((pass + 1)); } +bad() { echo " FAIL $*"; fail=$((fail + 1)); } +note() { echo " SKIP $*"; skip=$((skip + 1)); } +head_() { printf '\n== %s\n' "$*"; } + +state=$(A get-state) +if [ "$state" != "device" ]; then + echo "no authorized device (adb get-state: $state)" >&2 + exit 2 +fi + +density_snapshot=$(sh_ wm density) || density_snapshot= +size_snapshot=$(sh_ wm size) || size_snapshot= +orig_density=$(echo "$density_snapshot" | sed -n 's/.*Physical density: \([0-9]*\).*/\1/p' | head -1) +override_density=$(echo "$density_snapshot" | sed -n 's/.*Override density: \([0-9]*\).*/\1/p' | head -1) +override_size=$(echo "$size_snapshot" | sed -n 's/.*Override size: \([0-9]*x[0-9]*\).*/\1/p' | head -1) +ds=$(sh_ cmd device_state state 2>/dev/null) +orig_state=$(echo "$ds" | sed -n "s/.*Committed state: DeviceState{identifier=\([0-9]*\),.*/\1/p" | head -1) +pre_override=$(echo "$ds" | sed -n "s/.*Override state: DeviceState{identifier=\([0-9]*\),.*/\1/p" | head -1) + +density_changed=0 size_changed=0 fold_changed=0 +wm_override() { sed -n "s/.*Override $1: \\([0-9x]*\\).*/\\1/p" | head -1; } +restore_density() { + sh_ wm density "${override_density:-reset}" >/dev/null || return 1 + local current + current=$(sh_ wm density) || return 1 + echo "$current" | grep -q 'Physical density:' || return 1 + [ "$(echo "$current" | wm_override density)" = "$override_density" ] +} +restore_size() { + sh_ wm size "${override_size:-reset}" >/dev/null || return 1 + local current + current=$(sh_ wm size) || return 1 + echo "$current" | grep -q 'Physical size:' || return 1 + [ "$(echo "$current" | wm_override size)" = "$override_size" ] +} +# An override that was already in place (a test lab pins one) is put back; otherwise the request is cancelled. +restore_fold() { if [ -n "$pre_override" ]; then sh_ cmd device_state state "$pre_override" >/dev/null; else sh_ cmd device_state state reset >/dev/null; fi; } + +restore() { + local failed=0 + if [ "$density_changed" = 1 ]; then + if restore_density; then density_changed=0; else bad "could not restore display density"; failed=1; fi + fi + if [ "$size_changed" = 1 ]; then + if restore_size; then size_changed=0; else bad "could not restore window size"; failed=1; fi + fi + if [ "$fold_changed" = 1 ]; then + if restore_fold; then fold_changed=0; else bad "could not restore fold override"; failed=1; fi + fi + return "$failed" +} +finish() { + local status=$? + restore || status=1 + printf '\n%d passed, %d failed, %d skipped\n' "$pass" "$fail" "$skip" + [ "$fail" = 0 ] || status=1 + exit "$status" +} +trap finish EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +top_activity() { + sh_ dumpsys activity activities 2>/dev/null | sed -n 's/.*topResumedActivity=ActivityRecord{[^ ]* u[0-9]* \([^ ]*\) .*/\1/p' | head -1 +} +app_pid() { sh_ pidof "$pkg" | awk '{print $1}'; } +app_crashes() { + local out pat + out=$(sh_ logcat -b crash -d) || return 1 + pat=$(printf '%s' "$pkg" | sed 's/[.[\*^$]/\\&/g') + printf '%s\n' "$out" | grep -c -E "(Process: |Cmdline: |>>> )$pat([ ,<:]|$)" || true +} +relaunches_of() { # $1 = activity class fragment + sh_ logcat -b events -d 2>/dev/null | grep -E 'wm_(relaunch|destroy|create)_activity' | grep -c "$1" +} + +head_ "Device" +echo " model $(sh_ getprop ro.product.manufacturer) $(sh_ getprop ro.product.model)" +echo " android $(sh_ getprop ro.build.version.release) (API $(sh_ getprop ro.build.version.sdk)), One UI $(sh_ getprop ro.build.version.oneui)" +echo " kernel $(sh_ uname -r)" +page=$(sh_ getconf PAGE_SIZE) +echo " page size $page" +echo " soc $(sh_ getprop ro.soc.manufacturer) $(sh_ getprop ro.soc.model) ($(sh_ getprop ro.board.platform))" +echo " gpu $(sh_ cat /sys/class/kgsl/kgsl-3d0/gpu_model 2>/dev/null)" +echo " display $(sh_ wm size | tr '\n' ' ') $(sh_ wm density | tr '\n' ' ')" +[ "$page" = 4096 ] || [ "$page" = 16384 ] && ok "page size is $page" || bad "page size reads '$page'" + +head_ "Install and launch" +sh_ logcat -b crash -c >/dev/null +sh_ logcat -b events -c >/dev/null +if [ -n "$apk" ]; then + r=$(A install -r -t "$apk" | tail -1) + case $r in *Success*) ok "installed $(basename "$apk")" ;; *) bad "install: $r"; exit 1 ;; esac +fi +packages=$(sh_ pm list packages "$pkg") || { echo "could not query installed packages" >&2; exit 2; } +if ! printf '%s\n' "$packages" | grep -Fxq "package:$pkg"; then echo "package $pkg is not installed" >&2; exit 2; fi +if ! launch=$(sh_ am start -n "$pkg/.MainActivity") || printf '%s\n' "$launch" | grep -q '^Error'; then + bad "could not launch $pkg/.MainActivity" +fi +sleep 6 +pid=$(app_pid) +[ -n "$pid" ] && ok "process running (pid $pid)" || bad "the app has no process after launch" +t=$(top_activity) +case $t in + "$pkg"/*|*permissioncontroller*|*GrantPermissions*) ok "top activity: $t" ;; + *) bad "top activity is '$t'" ;; +esac +if c=$(app_crashes); then + [ "${c:-0}" = 0 ] && ok "nothing in the crash buffer belongs to the app" || bad "$c crash entries mention the app" +else + bad "could not read the crash buffer" +fi + +if [ "$do_density" = 1 ] && [ -n "$orig_density" ]; then + head_ "Density change" + target=$((orig_density * 5 / 4)) + before=$(top_activity); pid0=$(app_pid) + sh_ logcat -b events -c >/dev/null + density_changed=1 + wm_status=0 + sh_ wm density "$target" >/dev/null || wm_status=$? + sleep 6 + applied=$(sh_ wm density) || wm_status=1 + after=$(top_activity); pid1=$(app_pid) + if [ "$wm_status" -ne 0 ] || [ "$(echo "$applied" | wm_override density)" != "$target" ]; then + bad "wm density failed" + else + if [ -n "$pid1" ] && [ "$pid0" = "$pid1" ]; then + ok "same process after $orig_density -> $target dpi" + else + bad "process changed ($pid0 -> $pid1)" + fi + case $before in "$pkg"/*) + n=$(relaunches_of "${before#*/}") + [ "${n:-0}" = 0 ] && ok "$before was not recreated" || bad "$before was recreated ${n}x" + [ "$after" = "$before" ] && ok "same top activity after the change" || bad "top activity changed ($before -> $after)" + ;; *) note "top activity was not the app ($before)" ;; esac + fi + if restore_density; then + density_changed=0 + else + bad "could not restore display density" + fi + sleep 3 +elif [ "$do_density" = 1 ]; then + note "could not read the original display density" +fi + +if [ "$do_size" = 1 ]; then + head_ "Window size change" + phys=$(echo "$size_snapshot" | sed -n 's/.*Physical size: \([0-9]*\)x\([0-9]*\).*/\1 \2/p' | head -1) + set -- $phys + if [ -n "${1:-}" ]; then + w=$(( ($2 * 2 / 3) / 2 * 2 )); h=$1 # a narrower, taller window, like a cover screen + pid0=$(app_pid) + size_changed=1 + wm_status=0 + sh_ wm size "${w}x${h}" >/dev/null || wm_status=$? + sleep 6 + applied=$(sh_ wm size) || wm_status=1 + pid1=$(app_pid) + if [ "$wm_status" -ne 0 ] || [ "$(echo "$applied" | wm_override size)" != "${w}x${h}" ]; then + bad "wm size failed" + elif [ -n "$pid1" ] && [ "$pid0" = "$pid1" ]; then + ok "same process at ${w}x${h}" + else + bad "process changed ($pid0 -> $pid1)" + fi + if restore_size; then + size_changed=0 + else + bad "could not restore window size" + fi + sleep 3 + else + note "could not read the physical size" + fi +fi + +if [ "$do_fold" = 1 ]; then + head_ "Foldable states" + states=$(sh_ cmd device_state print-states 2>/dev/null) + if ! echo "$states" | grep -q "identifier"; then + note "no device_state service (not a foldable, or not permitted)" + elif [ -z "$orig_state" ]; then + note "could not read the current device_state identifier" + else + id_of() { echo "$states" | sed -n "s/.*identifier=\([0-9]*\), name='$1'.*/\1/p" | head -1; } + half=$(id_of HALF_OPENED); closed=$(id_of CLOSED) + cycle() { # $1 name $2 id + pid0=$(app_pid) + fold_changed=1 + sh_ cmd device_state state "$2" >/dev/null; sleep 8 + got=$(sh_ cmd device_state state | sed -n "s/.*Committed state: DeviceState{identifier=[0-9]*, name='\([A-Z_]*\)'.*/\1/p" | head -1) + pid1=$(app_pid) + [ "$got" = "$1" ] && ok "device state is $1" || note "asked for $1, committed '$got'" + [ -n "$pid1" ] && [ "$pid0" = "$pid1" ] && ok "same process in $1" || bad "process changed in $1 ($pid0 -> $pid1)" + restore_fold; sleep 6 + } + if [ -n "$half" ]; then cycle HALF_OPENED "$half"; else note "no HALF_OPENED state"; fi + if [ "$do_closed" = 1 ] && [ -n "$closed" ]; then + cycle CLOSED "$closed" + note "CLOSED turns the screens off: the session pauses (Background behaviour), Resume it from the app" + fi + got=$(sh_ cmd device_state state | sed -n "s/.*Committed state: DeviceState{identifier=\([0-9]*\),.*/\1/p" | head -1) + [ "$got" = "$orig_state" ] && ok "device state restored ($orig_state)" || bad "device state is $got, was $orig_state" + fi +fi + +head_ "Session log (debug builds)" +dir=$(sh_ run-as "$pkg" ls -t files/logs 2>/dev/null | head -1) +if [ -z "$dir" ] || echo "$dir" | grep -q -i "not debuggable\|unknown package"; then + note "no readable session folder (release build, or no session has run)" +else + echo " newest session $dir" + ev=$(sh_ run-as "$pkg" cat "files/logs/$dir/events.jsonl" 2>/dev/null) + echo "$ev" | grep -q '"frame.first"' && ok "first frame was drawn" || note "no frame.first in $dir" + echo "$ev" | grep -q '"session.failed"' && bad "session.failed: $(echo "$ev" | grep '"session.failed"' | tail -1 | cut -c1-160)" + fps=$(sh_ run-as "$pkg" cat "files/logs/$dir/app.log" 2>/dev/null | grep 'last 10 s:' | tail -1 | sed 's/.*last 10 s: //' | cut -c1-70) + [ -n "$fps" ] && echo " last stats $fps" + sh_ run-as "$pkg" cat "files/logs/$dir/device.txt" 2>/dev/null | grep -E 'Memory page size|^Kernel' | sed 's/^/ report /' +fi + +[ "$fail" = 0 ] diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index 2f9aac03f2..a34e97e356 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -66,3 +66,22 @@ library list, before anything is published. Sixteen more of Armada's patches are DRM/lease/HDR-on-KMS work for a native display, which this app's Wayland-hosted gamescope never reaches, or need a newer gamescope than the runtime has. + +- `0116-release-cursor-shm-buffers.patch` - this app: pointer cursor surfaces have no + X11/xdg window association, so routing their commits through `g_PendingCommits` + retained every old SHM buffer until the surface was destroyed. Ignore cursor-role + commits before taking the buffer lock; X11 cursor images still follow the existing + MouseCursor path. Window commits awaiting association are unchanged. + +The live regression probe is `tools/tests/test_gamescope_cursor_shm.py`. Run it +inside an active Gamescope session with access to that process's `/proc` fd +directory. It submits 20 distinct SHM cursor buffers and requires at most the +current buffer to remain open, then none after surface destruction. The +`--unassigned-control` variant omits the cursor role and verifies that all 20 +commits awaiting a window association remain queued until surface destruction. + +Device validation (2026-10-20): the stock component retained 20/20 cursor buffers; +the patched component retained 1/20, then 0 after destruction. The unassigned +control retained 20/20 and then 0. In Backpack Battles, two batches of ten touch +drags leaked 188 and 197 SHM descriptors before the fix; the same batches added +zero after the fix (112 total descriptors before and after each batch). diff --git a/tools/gamescope/patches/0116-release-cursor-shm-buffers.patch b/tools/gamescope/patches/0116-release-cursor-shm-buffers.patch new file mode 100644 index 0000000000..03b4d7fd0c --- /dev/null +++ b/tools/gamescope/patches/0116-release-cursor-shm-buffers.patch @@ -0,0 +1,15 @@ +--- a/src/wlserver.cpp ++++ b/src/wlserver.cpp +@@ -203,6 +203,12 @@ + } + + void xwayland_surface_commit(struct wlr_surface *wlr_surface) { ++ // Cursor surfaces never acquire an X11/xdg window association. Keeping their ++ // commits in g_PendingCommits pins every old SHM buffer until the cursor ++ // surface is destroyed. X11 cursor images are handled by MouseCursor. ++ if ( wlr_surface->role && strcmp( wlr_surface->role->name, "wl_pointer-cursor" ) == 0 ) ++ return; ++ + wlr_surface->current.committed = 0; + + wlserver_x11_surface_info *wlserver_x11_surface_info = get_wl_surface_info(wlr_surface)->x11_surface; diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index 39ee3c8a61..236ff8598e 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -3,7 +3,7 @@ set -u export HOME=${HOME:-/root} mode=${1:-desktop} shift || true -step() { echo "== STEP $(date -u +%H:%M:%S) $*"; } +step() { echo "== STEP $(date -u +%H:%M:%S.%3N) $*"; } steam_setup_failed() { echo "== steam: the Steam client could not be set up (status $1)" [ -z "${BL_STEAM_EXIT_FILE:-}" ] || printf '%s\n' "$1" > "$BL_STEAM_EXIT_FILE" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat index 7ed1eb71eb..3972faa9b3 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat @@ -182,6 +182,20 @@ SWITCH_JS = r""" })() """.replace("__BINDING__", SWITCH_BINDING) SESSION_SELECT = "/usr/bin/steamos-session-select" +# Steam opens its Steam Controller welcome tour at every start while the client setting +# controller_show_ibex_tour (CMsgClientSettings field 140014) is on, and only a finished tour turns it +# off; closing it leaves it on. The app's pad is an emulated controller, so the tour never applies. +# A pending firmware update still opens Steam's updater, which checks the update priority instead. +TOUR_JS = r""" +(() => { + let key = 140014 * 8; + const bytes = []; + while (key > 127) { bytes.push((key & 127) | 128); key = Math.floor(key / 128); } + bytes.push(key, 0); + SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes))); + return "off"; +})() +""" VR_BINDING = "droiddeckLaunchSteamVr" VR_HELPER = "/usr/local/bin/droiddeck-steamvr" VR_JS = r""" @@ -528,6 +542,11 @@ class Helper: page.call("Runtime.addBinding", {"name": BINDING}) page.call("Runtime.addBinding", {"name": VR_BINDING}) page.evaluate(VR_JS) + try: + page.evaluate(TOUR_JS) + except RuntimeError: + # The optional tour setting must not block the compat bridge. + pass if not self.steamos: page.call("Runtime.addBinding", {"name": SWITCH_BINDING}) page.evaluate(SWITCH_JS) diff --git a/tools/prepare_a850_driver_bundle.py b/tools/prepare_a850_driver_bundle.py new file mode 100644 index 0000000000..a24b848bd3 --- /dev/null +++ b/tools/prepare_a850_driver_bundle.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Package pinned local community A850 drivers; never download or execute drivers.""" + +import argparse +import hashlib +import io +import json +import os +from pathlib import Path +import stat +import struct +import tempfile +import zipfile + +ANDROID_SHA256 = '0cf849d068c875f6c469380ca1f74da1f757575bce53d4ef9c1f6d38677cbe8b' +LINUX_SHA256 = '40fc59506620001531b9bdd1c9152e104c6fb1f4c07773c4743b9d70deb87eec' +LIBRARY = 'libvulkan_freedreno.so' +VERSION = '20261012-a850exp1' +SOURCE = 'https://github.com/Droid-Deck/DroidDeck/issues/342' +README = f'''# Adreno 850 community experimental + +Manual opt-in experiment for DroidDeck; not native Adreno 850 support. +Source: community attachments to {SOURCE} +Android original: AdrenoTools-A850-experimental.zip, SHA256 {ANDROID_SHA256} +Linux original: A850-experimental.zip, SHA256 {LINUX_SHA256} + +These community binaries are patched to treat Adreno 850 as Adreno 840. +They have not been validated on the target phone by this project. They may +black-screen, hang, glitch, or fail to boot. They do not establish native 850 +support. Import and select this bundle manually; global auto selection is +unchanged. Use sysmem mode as advised in the original Linux metadata. + +Both original meta.json files, libraries, and Linux ICD JSON are preserved +byte-for-byte. No drivers are downloaded, executed, or rebuilt by this tool. +''' +NOTICE = f'''Community experimental binaries, distributed without a compatibility guarantee. +Original author attribution and release descriptions are in android/meta.json +and linux/meta.json. The412Banner is the original driver author; the community +attachment describes an experimental binary patch. Source: {SOURCE} +This wrapper makes no new license grant for the enclosed third-party binaries. +''' + + +def validate_elf(data, platform): + if (len(data) < 64 or data[:6] != b'\x7fELF\x02\x01' + or struct.unpack_from('> 16 + if entry.is_dir() or stat.S_IFMT(mode) not in (0, stat.S_IFREG) or entry.flag_bits & 1: + raise ValueError(f'{platform}: entry must be an unencrypted regular file') + files = {name: archive.read(name) for name in names} + meta = json.loads(files['meta.json']) + if not isinstance(meta, dict): + raise ValueError(f'{platform}: meta.json must be an object') + if platform == 'android' and meta.get('libraryName') != LIBRARY: + raise ValueError('android: incorrect meta.json libraryName') + if platform == 'linux': + if meta.get('libc') != 'glibc' or meta.get('kind') != 'linux-vulkan-icd': + raise ValueError('linux: incorrect meta.json libc/kind') + icd = json.loads(files['freedreno_icd.aarch64.json']) + if (not isinstance(icd, dict) or not isinstance(icd.get('ICD'), dict) + or icd['ICD'].get('library_path') != './' + LIBRARY): + raise ValueError('linux: incorrect ICD library_path') + validate_elf(files[LIBRARY], platform) + return files + + +def prepare_bundle(android, linux, output): + android, linux, output = map(Path, (android, linux, output)) + for source in (android, linux): + if source.resolve() == output.resolve() or (output.exists() and source.samefile(output)): + raise ValueError('output must differ from both input archives') + files = {} + for platform, source, digest in (('android', android, ANDROID_SHA256), ('linux', linux, LINUX_SHA256)): + files.update({f'{platform}/{name}': data for name, data in read_driver(source, platform, digest).items()}) + manifest = {'package': 'Adreno 850 community experimental', 'version': VERSION, 'tag': VERSION, + 'drivers': {'android': {'path': 'android'}, 'linux': {'path': 'linux'}}} + files['manifest.json'] = (json.dumps(manifest, indent=2, sort_keys=True) + '\n').encode() + files['README.md'] = README.encode() + files['NOTICE'] = NOTICE.encode() + temporary = None + try: + with tempfile.NamedTemporaryFile(dir=output.parent, prefix='.' + output.name + '.', delete=False) as target: + temporary = Path(target.name) + with zipfile.ZipFile(target, 'w', compression=zipfile.ZIP_STORED) as archive: + for name, data in sorted(files.items()): + info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) + info.create_system = 3 + info.external_attr = (stat.S_IFREG | 0o644) << 16 + archive.writestr(info, data) + target.flush() + os.fsync(target.fileno()) + os.replace(temporary, output) + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + return output + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--android', type=Path, required=True, help='Original AdrenoTools-A850-experimental.zip') + parser.add_argument('--linux', type=Path, required=True, help='Original A850-experimental.zip') + parser.add_argument('--output', type=Path, required=True, help='Destination DroidDeck DriverBundle zip') + args = parser.parse_args() + try: + result = prepare_bundle(args.android, args.linux, args.output) + except (OSError, ValueError, zipfile.BadZipFile, RuntimeError) as error: + parser.exit(1, f'error: {error}\n') + print(f'Created {result} (manual opt-in; experimental, no target-phone validation)') + + +if __name__ == '__main__': + main() diff --git a/tools/release/authorship_hook.py b/tools/release/authorship_hook.py new file mode 100644 index 0000000000..3129f76153 --- /dev/null +++ b/tools/release/authorship_hook.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +import os +from pathlib import Path +import subprocess +import sys + +from check_authorship import BOT, COAUTHOR, check_revision + + +def main(): + hook, *args = sys.argv[1:] + payload = sys.stdin.buffer.read() if hook == "pre-push" else None + if hook == "pre-push": + checked = set() + for line in payload.decode().splitlines(): + local_ref, local_sha, _, _ = line.split() + if local_sha == "0" * 40 or local_sha in checked: + continue + checked.add(local_sha) + _, errors = check_revision(local_sha) + if errors: + print("\n".join(errors), file=sys.stderr) + return 1 + else: + identity = subprocess.check_output(["git", "var", "GIT_AUTHOR_IDENT"], text=True) + if BOT.search(identity): + print("Bot commit author is forbidden: " + identity.strip(), file=sys.stderr) + return 1 + message = Path(args[0]) + original = message.read_text(encoding="utf-8") + cleaned = "".join(line for line in original.splitlines(keepends=True) + if not (COAUTHOR.match(line) and BOT.search(line))) + if cleaned != original: + message.write_text(cleaned, encoding="utf-8") + print("Removed bot co-author trailers; human credits preserved.", file=sys.stderr) + legacy = Path(__file__).with_name("legacy-" + hook) + if legacy.exists() and os.access(legacy, os.X_OK): + return subprocess.run([str(legacy), *args], input=payload).returncode + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/release/check_authorship.py b/tools/release/check_authorship.py new file mode 100644 index 0000000000..9d952acc0d --- /dev/null +++ b/tools/release/check_authorship.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Reject bot authors and bot co-author trailers without executing reviewed code.""" +import argparse +import json +import re +import subprocess +import sys + +BOT = re.compile( + r"Claude|Anthropic|OpenAI|ChatGPT|GPT|Copilot|Cursor|Gemini|Codex|Devin|" + r"Windsurf|Codeium|Amazon Q|Tabnine|Cody|\[bot\]|github-actions|" + r"dependabot|renovate(?:\[bot\])?", + re.IGNORECASE, +) +COAUTHOR = re.compile(r"^\s*Co-authored-by\s*:", re.IGNORECASE) + + +def commit_violations(commit, raw): + header, separator, message = raw.partition(b"\n\n") + if not separator: + return [f"{commit}: invalid commit object"] + authors = [line[7:] for line in header.splitlines() if line.startswith(b"author ")] + if len(authors) != 1: + return [f"{commit}: expected one author"] + identity = authors[0].decode("utf-8", errors="replace") + errors = [] + if BOT.search(identity): + errors.append(f"{commit}: bot author: {identity}") + for line in message.decode("utf-8", errors="replace").splitlines(): + if COAUTHOR.match(line) and BOT.search(line): + errors.append(f"{commit}: bot co-author: {line.strip()}") + return errors + + +def event_violations(event): + pr = event.get("pull_request", {}) + user = pr.get("user", {}) + errors = [] + if user.get("type") == "Bot" or BOT.search(user.get("login", "")): + errors.append("pull request: bot authorship is forbidden") + for field in ("title", "body"): + for line in (pr.get(field) or "").splitlines(): + if COAUTHOR.match(line) and BOT.search(line): + errors.append(f"pull request {field}: bot co-author trailer") + return errors + + +def check_revision(revision): + commits = subprocess.check_output(["git", "rev-list", revision], text=True).splitlines() + errors = [] + with subprocess.Popen(["git", "cat-file", "--batch"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) as process: + for commit in commits: + process.stdin.write((commit + "\n").encode("ascii")) + process.stdin.flush() + descriptor = process.stdout.readline().split() + if len(descriptor) != 3 or descriptor[1] != b"commit": + raise RuntimeError(f"Cannot read commit {commit}") + size = int(descriptor[2]) + raw = process.stdout.read(size) + if len(raw) != size or process.stdout.read(1) != b"\n": + raise RuntimeError(f"Truncated commit {commit}") + errors.extend(commit_violations(commit, raw)) + process.stdin.close() + if process.wait() != 0: + raise RuntimeError("git cat-file failed") + return commits, errors + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("revision") + parser.add_argument("--event") + args = parser.parse_args() + commits, errors = check_revision(args.revision) + if args.event: + with open(args.event, encoding="utf-8") as source: + errors.extend(event_violations(json.load(source))) + for error in errors: + print(f"::error::{error}", file=sys.stderr) + if errors: + return 1 + print(f"Human authorship verified for {len(commits)} commits.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/release/install_authorship_hooks.py b/tools/release/install_authorship_hooks.py new file mode 100644 index 0000000000..dae4eb5177 --- /dev/null +++ b/tools/release/install_authorship_hooks.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Install shared worktree hooks while preserving existing executable hooks.""" +from pathlib import Path +import shutil +import subprocess + +MARKER = "# DroidDeck human authorship hook" + + +def install(): + common = Path(subprocess.check_output(["git", "rev-parse", "--git-common-dir"], text=True).strip()).resolve() + configured = subprocess.run(["git", "config", "--get", "core.hooksPath"], capture_output=True, text=True) + hooks = Path(configured.stdout.strip()).resolve() if configured.returncode == 0 else common / "hooks" + target = common / "authorship-hooks" + hooks.mkdir(parents=True, exist_ok=True) + target.mkdir(parents=True, exist_ok=True) + for name in ("check_authorship.py", "authorship_hook.py"): + shutil.copyfile(Path(__file__).with_name(name), target / name) + for name in ("prepare-commit-msg", "commit-msg", "pre-push"): + path = hooks / name + if path.exists() and MARKER not in path.read_text(errors="replace"): + legacy = target / ("legacy-" + name) + if legacy.exists(): + raise RuntimeError(f"Refusing to replace existing saved hook: {legacy}") + shutil.copy2(path, legacy) + path.write_text( + '#!/bin/sh\n' + MARKER + '\n' + 'exec python3 "$(git rev-parse --git-common-dir)/authorship-hooks/authorship_hook.py" ' + + name + ' "$@"\n' + ) + path.chmod(0o755) + print(f"Human authorship hooks installed in {hooks}") + + +if __name__ == "__main__": + install() diff --git a/tools/release/validate_apk.py b/tools/release/validate_apk.py new file mode 100644 index 0000000000..8ed51ebf19 --- /dev/null +++ b/tools/release/validate_apk.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Publish the APK result only after trusted source and metadata validation.""" +import json +import os +import subprocess +from urllib.parse import urlencode + +from check_authorship import check_revision, event_violations + + +def api(path, *args): + return json.loads(subprocess.check_output(["gh", "api", path, *args], text=True)) + + +def compilation_state(run, jobs): + for job in jobs: + if job["name"] in ("Compile and test APK", "Build APK"): + if job["status"] != "completed": + return "pending" + return "success" if job["conclusion"] == "success" else "failure" + return "failure" if run["status"] == "completed" else "pending" + + +def fetch_source(ref, sha): + subprocess.run(["git", "fetch", "--no-tags", "origin", ref], check=True) + fetched = subprocess.check_output(["git", "rev-parse", "FETCH_HEAD"], text=True).strip() + if fetched != sha: + raise RuntimeError("Pull request changed while validating") + + +def documentation_only(sha): + base = subprocess.check_output(["git", "merge-base", "origin/main", sha], text=True).strip() + paths = subprocess.check_output(["git", "diff", "--no-renames", "--name-only", "-z", base, sha]).split(b"\0") + return all(path.endswith(b".md") or path in (b"LICENSE", b".gitignore") for path in paths if path) + + +def main(): + with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as source: + event = json.load(source) + repo = os.environ["GITHUB_REPOSITORY"] + event_name = os.environ["GITHUB_EVENT_NAME"] + pr_number = event.get("number") if event_name == "pull_request_target" else None + if event_name == "workflow_dispatch": + pr_number = int(event.get("inputs", {}).get("pr_number") or 0) + run = event.get("workflow_run", {}) + expected = event.get("pull_request", {}).get("head", {}).get("sha") + if event_name == "workflow_run": + expected = run["head_sha"] + if run["event"] == "pull_request": + prs = api(f"repos/{repo}/commits/{expected}/pulls") + pr_number = next((pr["number"] for pr in prs + if pr["state"] == "open" and pr["head"]["sha"] == expected), None) + if pr_number is None: + print("Ignoring a superseded or closed pull request build") + return + elif run["head_branch"] != event["repository"]["default_branch"]: + return + if pr_number: + pr = api(f"repos/{repo}/pulls/{pr_number}") + sha = pr["head"]["sha"] + if pr["state"] != "open" or (expected and sha != expected): + print("Ignoring a superseded or closed pull request event") + return + ref = f"refs/pull/{pr_number}/head" + source_event = "pull_request" + else: + pr = None + sha = expected or event.get("after") or os.environ["GITHUB_SHA"] + ref = sha + source_event = "push" + state = "failure" + description = "APK source validation failed" + target = f"https://github.com/{repo}/actions/runs/{os.environ['GITHUB_RUN_ID']}" + try: + fetch_source(ref, sha) + commits, errors = check_revision(sha) + if pr: + errors.extend(event_violations({"pull_request": pr})) + if errors: + raise RuntimeError("\n".join(errors)) + print(f"Source and metadata validated for {len(commits)} commits") + if pr and documentation_only(sha): + state = "success" + description = "Source validated; no APK source changes" + return + query = urlencode({"head_sha": sha, "event": source_event, "per_page": 20}) + runs = api(f"repos/{repo}/actions/workflows/build.yml/runs?{query}")["workflow_runs"] + runs = [item for item in runs if item["head_sha"] == sha] + if runs: + latest = max(runs, key=lambda item: item["id"]) + jobs = api(f"repos/{repo}/actions/runs/{latest['id']}/jobs?per_page=100")["jobs"] + state = compilation_state(latest, jobs) + target = latest["html_url"] + else: + state = "pending" + description = {"pending": "Source validated; awaiting APK compilation", + "success": "Source validation and APK compilation passed", + "failure": "APK compilation failed"}[state] + finally: + api(f"repos/{repo}/statuses/{sha}", "--method", "POST", + "-f", "context=Build APK", "-f", f"state={state}", + "-f", f"description={description}", "-f", f"target_url={target}") + + +if __name__ == "__main__": + main() diff --git a/tools/tests/test_a850_driver_bundle.py b/tools/tests/test_a850_driver_bundle.py new file mode 100644 index 0000000000..d207a63d21 --- /dev/null +++ b/tools/tests/test_a850_driver_bundle.py @@ -0,0 +1,164 @@ +import hashlib +import importlib.util +import json +from pathlib import Path +import struct +import stat +import tempfile +import unittest +from unittest import mock +import zipfile + +spec = importlib.util.spec_from_file_location( + 'prepare_a850_driver_bundle', Path(__file__).resolve().parents[1] / 'prepare_a850_driver_bundle.py') +prepare = importlib.util.module_from_spec(spec) +spec.loader.exec_module(prepare) + + +class A850BundleTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.android = self.root / 'android.zip' + self.linux = self.root / 'linux.zip' + self.output = self.root / 'bundle.zip' + self.android_files = self.files('android') + self.linux_files = self.files('linux') + self.write(self.android, self.android_files) + self.write(self.linux, self.linux_files) + + def files(self, platform): + elf = bytearray(64) + elf[:6] = b'\x7fELF\x02\x01' + struct.pack_into(' 1 +0000\n\n" + message).encode() + + def test_bot_primary_author_is_rejected_without_a_trailer(self): + for author in ("OpenAI Codex ", "Claude ", + "github-actions[bot] "): + with self.subTest(author=author): + self.assertTrue(check.commit_violations("abc", self.commit(author=author))) + + def test_bot_trailers_are_rejected_even_after_human_trailers(self): + message = "Fix\n\nCo-authored-by: Resul Övür \nco-AUTHORED-by: OpenAI Codex \n" + self.assertEqual(1, len(check.commit_violations("abc", self.commit(message=message)))) + + def test_human_authors_and_human_coauthors_are_preserved(self): + message = "Fix the Codex configuration\n\nCo-authored-by: Resul Övür \n" + self.assertEqual([], check.commit_violations("abc", self.commit(message=message))) + + def test_record_separator_in_message_does_not_hide_a_bot_trailer(self): + self.assertTrue(check.commit_violations("abc", self.commit(message="Fix\x1e\nCo-authored-by: Claude \n"))) + + def test_pr_metadata_cannot_add_a_bot_to_the_squash_message(self): + for field in ("title", "body"): + self.assertTrue(check.event_violations({"pull_request": {field: "Co-authored-by: Copilot "}})) + + def test_bot_pr_author_is_rejected(self): + self.assertTrue(check.event_violations({"pull_request": {"user": {"login": "service", "type": "Bot"}}})) + + def test_missing_author_fails_closed(self): + self.assertTrue(check.commit_violations("abc", b"tree 000\n\nmessage\n")) + + +class InstalledHooksTest(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.repo = Path(self.directory.name) + self.git("init", "-q") + self.git("config", "user.name", "Human Contributor") + self.git("config", "user.email", "human@example.com") + installer = path.with_name("install_authorship_hooks.py") + subprocess.run([sys.executable, str(installer)], cwd=self.repo, check=True, capture_output=True) + (self.repo / "file").write_text("content") + self.git("add", "file") + + def tearDown(self): + self.directory.cleanup() + + def git(self, *args): + return subprocess.run(["git", *args], cwd=self.repo, text=True, capture_output=True) + + def test_explicit_bot_author_override_is_blocked(self): + result = self.git("commit", "--author=OpenAI Codex ", "-m", "Fix") + self.assertNotEqual(0, result.returncode, result.stdout + result.stderr) + self.assertIn("Bot commit author is forbidden", result.stderr) + + def test_no_verify_does_not_skip_automatic_trailer_scrubbing(self): + result = self.git("commit", "--no-verify", "-m", "Fix\n\nCo-authored-by: Another Human \nCo-authored-by: Claude ") + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + message = self.git("log", "-1", "--format=%B").stdout + self.assertNotIn("noreply@anthropic.com", message) + self.assertIn("Co-authored-by: Another Human ", message) + + def test_human_commit_and_human_coauthor_are_allowed(self): + result = self.git("commit", "-m", "Fix\n\nCo-authored-by: Another Human ") + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_device_smoke.py b/tools/tests/test_device_smoke.py new file mode 100644 index 0000000000..9afeb919f9 --- /dev/null +++ b/tools/tests/test_device_smoke.py @@ -0,0 +1,123 @@ +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "device-smoke.sh" +FAKE_ADB = r'''#!/usr/bin/env python3 +import json, os, shlex, sys +from pathlib import Path +p = Path(os.environ["SMOKE_STATE"]) +s = json.loads(p.read_text()) +a = sys.argv[1:] +if a == ["get-state"]: + print("device") +elif a[:1] == ["shell"]: + a = shlex.split(a[1]) + if a[:1] == ["wm"]: + kind = a[1] + if len(a) == 2: + if s.get("unreadable") == kind: + print("permission denied") + else: + print("Physical " + kind + ": " + ("400" if kind == "density" else "1080x1920")) + if s.get(kind): print("Override " + kind + ": " + s[kind]) + else: + value = a[2] + s["writes"].append([kind, value]) + restoring = value in ("reset", "420", "1000x1800") + if not (s.get("ignored") == kind or restoring and s.get("restore_ignored") == kind): + s[kind] = "" if value == "reset" else value + p.write_text(json.dumps(s)) + elif a[:1] == ["getconf"]: print("4096") + elif a[:1] == ["pidof"]: print("123") + elif a[:2] == ["dumpsys", "activity"]: + print("topResumedActivity=ActivityRecord{abc u0 com.droiddeck.launcher/.MainActivity t1}") + elif a[:3] == ["pm", "list", "packages"]: + if s.get("query_failed"): sys.exit(1) + print("package:" + s.get("package", "com.droiddeck.launcher")) + elif a[:2] == ["am", "start"] and s.get("launch_failed"): + print("Error: activity could not be started") + sys.exit(1 if s["launch_failed"] == "exit" else 0) + elif a[:1] == ["run-as"]: + if s.get("session"): + s.setdefault("log_commands", []).append(a) + p.write_text(json.dumps(s)) + if "ls" in a: print(s["session"]) + else: print("package not debuggable") +''' + + +class DeviceSmokeTest(unittest.TestCase): + def run_smoke(self, **scenario): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + adb = root / "adb" + adb.write_text(FAKE_ADB) + adb.chmod(0o755) + sleep = root / "sleep" + sleep.write_text("#!/bin/sh\nexit 0\n") + sleep.chmod(0o755) + state = root / "state.json" + state.write_text(json.dumps({"density": "", "size": "", "writes": [], **scenario})) + env = dict(os.environ, ADB=str(adb), SMOKE_STATE=str(state), PATH=str(root) + os.pathsep + os.environ["PATH"]) + result = subprocess.run(["bash", str(SCRIPT), "--no-fold"], env=env, capture_output=True, text=True, timeout=30) + return result, json.loads(state.read_text()) + + def test_restores_preexisting_display_overrides(self): + result, state = self.run_smoke(density="420", size="1000x1800") + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + self.assertEqual("420", state["density"]) + self.assertEqual("1000x1800", state["size"]) + + def test_ignored_display_changes_do_not_pass(self): + for kind in ("density", "size"): + with self.subTest(kind=kind): + result, state = self.run_smoke(ignored=kind) + self.assertEqual(1, result.returncode, result.stdout) + self.assertIn("wm " + kind + " failed", result.stdout) + self.assertNotIn("PASS same process " + ("after" if kind == "density" else "at"), result.stdout) + self.assertEqual("", state[kind]) + + def test_ignored_restore_remains_a_failure_and_is_retried_on_exit(self): + for kind in ("density", "size"): + with self.subTest(kind=kind): + result, state = self.run_smoke(restore_ignored=kind) + self.assertEqual(1, result.returncode, result.stdout) + self.assertIn("could not restore", result.stdout) + self.assertNotEqual("", state[kind]) + self.assertEqual(2, state["writes"].count([kind, "reset"])) + + def test_unreadable_original_settings_are_not_changed(self): + for kind in ("density", "size"): + with self.subTest(kind=kind): + result, state = self.run_smoke(unreadable=kind) + self.assertEqual(0, result.returncode, result.stdout) + self.assertFalse(any(item[0] == kind for item in state["writes"])) + + def test_package_filter_does_not_accept_another_variant_or_a_failed_query(self): + for scenario in ({"package": "com.droiddeck.launcher.debug"}, {"query_failed": True}): + with self.subTest(scenario=scenario): + result, state = self.run_smoke(**scenario) + self.assertEqual(2, result.returncode, result.stdout) + self.assertEqual([], state["writes"]) + + def test_failed_launch_is_not_masked_by_an_existing_process(self): + for failure in ("exit", "message"): + with self.subTest(failure=failure): + result, _ = self.run_smoke(launch_failed=failure) + self.assertEqual(1, result.returncode, result.stdout) + self.assertIn("could not launch", result.stdout) + + def test_session_name_remains_one_remote_argument(self): + session = "x';id;#" + result, state = self.run_smoke(session=session) + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + self.assertIn(["run-as", "com.droiddeck.launcher", "cat", "files/logs/" + session + "/events.jsonl"], state["log_commands"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_gamescope_cursor_shm.py b/tools/tests/test_gamescope_cursor_shm.py new file mode 100644 index 0000000000..35ca27acb2 --- /dev/null +++ b/tools/tests/test_gamescope_cursor_shm.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Live regression probe; run inside a running Gamescope session. + +Requires Python 3, WAYLAND_DISPLAY, XDG_RUNTIME_DIR and access to Gamescope's +/proc//fd. Creates only a temporary surface with the cursor role; it does +not take pointer focus or change game/save files. Affected Gamescope retains all +20 SHM allocations; fixed Gamescope retains at most the current cursor buffer. +""" +import os +import socket +import struct +import time +import json +import array +import argparse +from pathlib import Path + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--unassigned-control', action='store_true', help='verify that window buffers awaiting association remain queued') + args = parser.parse_args() + s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + s.settimeout(2) + s.connect(os.path.join(os.environ['XDG_RUNTIME_DIR'], os.environ['WAYLAND_DISPLAY'])) + U = lambda *v: struct.pack('<' + 'I' * len(v), *v) + + def string(v): + b = v.encode() + b'\x00' + return U(len(b)) + b + b'\x00' * (-len(b) % 4) + + def send(obj, op, p=b'', fd=None): + b = U(obj, len(p) + 8 << 16 | op) + p + if fd is None: + s.sendall(b) + else: + s.sendmsg([b], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array('i', [fd]))]) + nextid = 2 + pids = [] + for process in Path('/proc').iterdir(): + if not process.name.isdigit(): + continue + try: + if (process / 'comm').read_text().strip() == 'gamescope': + pids.append(process) + except (FileNotFoundError, PermissionError): + pass + assert len(pids) == 1, f'expected one Gamescope process, found {[p.name for p in pids]}' + fd_dir = pids[0] / 'fd' + + def alloc(): + nonlocal nextid + nextid += 1 + return nextid + pending = b'' + globals = {} + + def roundtrip(): + nonlocal pending + cb = alloc() + send(1, 0, U(cb)) + while True: + while len(pending) >= 8: + obj, h = struct.unpack_from('> 16 + op = h & 65535 + if len(pending) < n: + break + p = pending[8:n] + pending = pending[n:] + if obj == 1 and op == 0: + raise RuntimeError('wayland error ' + repr(p)) + if obj == 2 and op == 0: + name, l = struct.unpack_from(' + + + + + + + + + + + + diff --git a/tools/viture/viture-v2-driver-check/README.md b/tools/viture/viture-v2-driver-check/README.md new file mode 100644 index 0000000000..6255aa2a27 --- /dev/null +++ b/tools/viture/viture-v2-driver-check/README.md @@ -0,0 +1,53 @@ +# Production VITURE v2 driver hardware check + +This harness calls the actual production `VitureV2Link.Companion.open` and packages +the freshly compiled `VitureV2Link*.class`, `VitureV2Protocol*.class`, and +`GlassesLink*.class` files from `app/build/tmp/kotlin-classes/debug`. It contains no +USB transport or protocol implementation of its own and no vendor SDK or native +library. The Kotlin standard library version matches the root Gradle build, 2.1.0. +The default build relies on Gradle's source/dependency checks to refresh classes +and rejects unexpected application-class dependencies, including an old +orientation-helper dependency. Source and bytecode hashes are recorded together; +file timestamps are not used because Gradle can restore classes from its cache. + +Build from the workspace with: + +```powershell +./tools/viture/viture-v2-driver-check/build.ps1 +``` + +This first invokes `:app:compileDebugKotlin -PvitureSdkDir=`. If the parent task just +completed that compile, pass `-SkipCompile` to package those classes without starting +another Gradle build. That option requires the caller to ensure the classes are +current. The output is +`tools/viture/viture-v2-driver-check/out/viture-v2-driver-check-debug.apk`. +SDK discovery uses `ANDROID_HOME`, `ANDROID_SDK_ROOT`, then `%LOCALAPPDATA%\Android\Sdk`. +JDK discovery uses `JAVA_HOME`, the optional `%USERPROFILE%\.jdks\jbr-17.0.9`, then +`javac.exe` on PATH. Explicit `-Sdk` and `-Java` override discovery. Kotlin cache +discovery respects `GRADLE_USER_HOME`, falling back to `%USERPROFILE%\.gradle`. +APK assets contain the upstream MIT license and a runtime manifest of the exact +production-class SHA256 hashes and Kotlin library hash. Every session logs this +manifest. The documented upstream protocol itself was derived from third-party +vendor SDK captures; this harness uses the existing SDK-free production driver. + +Only an attached `35ca:1301` Pro 2 can be opened. After USB permission, the real +driver bootstraps its pose stream. `onReady` is posted to the main handler so the +link assignment is complete before control commands. The harness sends the +controller's internal IMU-off command, checks for zero new pose callbacks over +500 ms, resumes, captures for 10..15 seconds (default 12), pauses again, checks +another 500 ms, and closes the driver. A watchdog starts closure at 23.5 seconds, +reserving the driver's maximum 1.5-second join for a 25-second test limit after +permission. Android scheduling or system stalls can extend elapsed wall time. + +```powershell +adb shell am start -n com.droiddeck.viturev2check/.MainActivity --ez auto true --ei seconds 12 +``` + +JSONL logs are under +`/data/user/0/com.droiddeck.viturev2check/files/checks/driver-check-.jsonl`. +They include every callback packet with actual length and base64 bytes, the exact +shared `xyzw` quaternion delivered by production code, tracking/ready events, +pause-window counts, errors, bad frames, total and capture pose counts, sample +rate, and final state. This checks the real driver's hardware/session behavior; +it does not run the full application UI or establish the user's physical axis +and recentering experience. Reopen the activity for a separate check. diff --git a/tools/viture/viture-v2-driver-check/assets/LICENSE.kotlin-Apache-2.0 b/tools/viture/viture-v2-driver-check/assets/LICENSE.kotlin-Apache-2.0 new file mode 100644 index 0000000000..f433b1a53f --- /dev/null +++ b/tools/viture/viture-v2-driver-check/assets/LICENSE.kotlin-Apache-2.0 @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/tools/viture/viture-v2-driver-check/assets/LICENSE.viture-v2 b/tools/viture/viture-v2-driver-check/assets/LICENSE.viture-v2 new file mode 100644 index 0000000000..9c1d9de29a --- /dev/null +++ b/tools/viture/viture-v2-driver-check/assets/LICENSE.viture-v2 @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Holger Bartnick + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/viture/viture-v2-driver-check/assets/NOTICE.txt b/tools/viture/viture-v2-driver-check/assets/NOTICE.txt new file mode 100644 index 0000000000..11a2ce316c --- /dev/null +++ b/tools/viture/viture-v2-driver-check/assets/NOTICE.txt @@ -0,0 +1,12 @@ +The VITURE v2 protocol in the packaged production DroidDeck driver is adapted from +elasticjava/viture-v2, copyright (c) 2026 Holger Bartnick, under the MIT license. +Pinned upstream commit: ece8c30485f7d357fefa362ae74f3eabac9b3899. +See LICENSE.viture-v2 in these APK assets for the complete license. + +The APK packages actual compiled DroidDeck VitureV2Link, VitureV2Protocol, and +GlassesLink classes and the Kotlin standard library 2.1.0. Kotlin is copyright +JetBrains and contributors and distributed under Apache License 2.0: +https://www.apache.org/licenses/LICENSE-2.0 +See LICENSE.kotlin-Apache-2.0 in these APK assets for the complete license terms. + +No vendor SDK or vendor native libraries are included. diff --git a/tools/viture/viture-v2-driver-check/build.ps1 b/tools/viture/viture-v2-driver-check/build.ps1 new file mode 100644 index 0000000000..7c34e150e9 --- /dev/null +++ b/tools/viture/viture-v2-driver-check/build.ps1 @@ -0,0 +1,117 @@ +param( + [string]$Sdk, + [string]$Java = $env:JAVA_HOME, + [switch]$SkipCompile +) +$ErrorActionPreference = 'Stop' +if (-not $Sdk) { + if ($env:ANDROID_HOME) { $Sdk = $env:ANDROID_HOME } + elseif ($env:ANDROID_SDK_ROOT) { $Sdk = $env:ANDROID_SDK_ROOT } + elseif ($env:LOCALAPPDATA) { $Sdk = Join-Path $env:LOCALAPPDATA 'Android\Sdk' } + else { throw 'Set ANDROID_HOME / ANDROID_SDK_ROOT or pass -Sdk.' } +} +if (-not $Java) { + $fallbackJdk = Join-Path $env:USERPROFILE '.jdks\jbr-17.0.9' + $javacCommand = Get-Command javac.exe -ErrorAction SilentlyContinue + if (Test-Path -LiteralPath (Join-Path $fallbackJdk 'bin\javac.exe')) { $Java = $fallbackJdk } + elseif ($javacCommand) { $Java = Split-Path (Split-Path $javacCommand.Source -Parent) -Parent } +} +if (-not $Java -or -not (Test-Path -LiteralPath (Join-Path $Java 'bin\javac.exe'))) { + throw 'Set JAVA_HOME or pass -Java with a JDK containing bin\javac.exe.' +} +$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..\..')) +$output = Join-Path $PSScriptRoot 'out' +$buildId = [Guid]::NewGuid().ToString('N') +$classes = Join-Path $output ('classes-' + $buildId) +$production = Join-Path $output ('production-' + $buildId) +$productionPackage = Join-Path $production 'com\droiddeck\launcher\glasses' +$assets = Join-Path $output ('assets-' + $buildId) +$dex = Join-Path $output ('dex-' + $buildId) +$buildTools = Join-Path $Sdk 'build-tools\36.0.0' +$androidJar = Join-Path $Sdk 'platforms\android-34\android.jar' +$compiled = Join-Path $repo 'app\build\tmp\kotlin-classes\debug\com\droiddeck\launcher\glasses' +$stdlibVersion = '2.1.0' +$gradleCacheRoot = if ($env:GRADLE_USER_HOME) { $env:GRADLE_USER_HOME } else { Join-Path $env:USERPROFILE '.gradle' } +$stdlibDirectory = Join-Path $gradleCacheRoot ('caches\modules-2\files-2.1\org.jetbrains.kotlin\kotlin-stdlib\' + $stdlibVersion) +$stdlibFiles = @(Get-ChildItem -LiteralPath $stdlibDirectory -Recurse -File | Where-Object Name -EQ ('kotlin-stdlib-' + $stdlibVersion + '.jar')) +if ($stdlibFiles.Count -ne 1) { throw "Expected one cached Kotlin stdlib $stdlibVersion jar." } +$stdlib = $stdlibFiles[0].FullName +$unsigned = Join-Path $output 'viture-v2-driver-check-unsigned.apk' +$aligned = Join-Path $output 'viture-v2-driver-check-aligned.apk' +$apk = Join-Path $output 'viture-v2-driver-check-debug.apk' +$classJar = Join-Path $output 'harness.jar' +$productionJar = Join-Path $output 'production-driver.jar' +$previousJavaHome = $env:JAVA_HOME +try { + $env:JAVA_HOME = $Java + if (-not $SkipCompile) { + Push-Location -LiteralPath $repo + try { + & (Join-Path $repo 'gradlew.bat') ':app:compileDebugKotlin' '-PvitureSdkDir=' + if ($LASTEXITCODE -ne 0) { throw 'Production Kotlin compilation failed.' } + } finally { Pop-Location } + } + $manifestSources = @() + foreach ($pair in @( + @('VitureV2Link.class', 'VitureV2Link.kt'), + @('VitureV2Protocol.class', 'VitureV2Protocol.kt'), + @('GlassesLink.class', 'GlassesHardware.kt') + )) { + $binary = Get-Item -LiteralPath (Join-Path $compiled $pair[0]) + $source = Get-Item -LiteralPath (Join-Path $repo ('app\src\main\java\com\droiddeck\launcher\glasses\' + $pair[1])) + $manifestSources += [ordered]@{ name = $source.Name; sha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $source.FullName).Hash } + } + New-Item -ItemType Directory -Force -Path $output, $classes, $productionPackage, $assets, $dex | Out-Null + $classFiles = @(Get-ChildItem -LiteralPath $compiled -File | Where-Object { + $_.Name -like 'VitureV2Link*.class' -or $_.Name -like 'VitureV2Protocol*.class' -or $_.Name -like 'GlassesLink*.class' + }) + if ($classFiles.Count -lt 3) { throw 'Production class selection is incomplete.' } + $manifestClasses = @() + foreach ($classFile in $classFiles) { + Copy-Item -LiteralPath $classFile.FullName -Destination $productionPackage + $manifestClasses += [ordered]@{ name = $classFile.Name; sha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $classFile.FullName).Hash } + } + & (Join-Path $Java 'bin\jar.exe') cf $productionJar -C $production . + if ($LASTEXITCODE -ne 0) { throw 'Production jar creation failed.' } + $dependencies = & (Join-Path $Java 'bin\jdeps.exe') -verbose:class -filter:none $productionJar + if ($LASTEXITCODE -ne 0) { throw 'Production dependency inspection failed.' } + foreach ($line in $dependencies) { + if ($line -match '->\s+(com\.droiddeck\.launcher\.glasses\.\S+)') { + if ($Matches[1] -notmatch '^com\.droiddeck\.launcher\.glasses\.(VitureV2Link|VitureV2Protocol|GlassesLink)(\$|$)') { + throw ('Unexpected production dependency: ' + $Matches[1] + '. Recompile the current isolated driver source.') + } + } + } + Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'assets\LICENSE.viture-v2') -Destination $assets + Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'assets\NOTICE.txt') -Destination $assets + Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'assets\LICENSE.kotlin-Apache-2.0') -Destination $assets + $runtimeManifest = [ordered]@{ + source = 'Actual app/build/tmp/kotlin-classes/debug production bytecode; not reimplemented' + upstreamCommit = 'ece8c30485f7d357fefa362ae74f3eabac9b3899' + builtUtc = [DateTime]::UtcNow.ToString('o') + kotlinStdlibVersion = $stdlibVersion + kotlinStdlibSha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $stdlib).Hash + productionJarSha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $productionJar).Hash + sources = $manifestSources + classes = $manifestClasses + } + $runtimeManifest | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $assets 'runtime-manifest.json') -Encoding utf8 + & (Join-Path $Java 'bin\javac.exe') --release 8 -classpath ($androidJar + ';' + $productionJar + ';' + $stdlib) -encoding UTF-8 -d $classes (Join-Path $PSScriptRoot 'src\com\droiddeck\viturev2check\MainActivity.java') + if ($LASTEXITCODE -ne 0) { throw 'Harness Java compilation failed.' } + & (Join-Path $Java 'bin\jar.exe') cf $classJar -C $classes . + if ($LASTEXITCODE -ne 0) { throw 'Harness jar creation failed.' } + & (Join-Path $buildTools 'd8.bat') --min-api 26 --lib $androidJar --output $dex $classJar $productionJar $stdlib + if ($LASTEXITCODE -ne 0) { throw 'D8 failed.' } + & (Join-Path $buildTools 'aapt2.exe') link --manifest (Join-Path $PSScriptRoot 'AndroidManifest.xml') -A $assets -I $androidJar -o $unsigned --min-sdk-version 26 --target-sdk-version 34 + if ($LASTEXITCODE -ne 0) { throw 'Manifest linking failed.' } + & (Join-Path $Java 'bin\jar.exe') uf $unsigned -C $dex classes.dex + if ($LASTEXITCODE -ne 0) { throw 'Dex insertion failed.' } + & (Join-Path $buildTools 'zipalign.exe') -f 4 $unsigned $aligned + if ($LASTEXITCODE -ne 0) { throw 'APK alignment failed.' } + & (Join-Path $buildTools 'apksigner.bat') sign --ks (Join-Path $repo 'keystore\testkey.p12') --ks-key-alias testkey --ks-pass pass:android --key-pass pass:android --out $apk $aligned + if ($LASTEXITCODE -ne 0) { throw 'APK signing failed.' } + & (Join-Path $buildTools 'apksigner.bat') verify --verbose $apk + if ($LASTEXITCODE -ne 0) { throw 'APK verification failed.' } + Get-FileHash -Algorithm SHA256 -LiteralPath $apk + Write-Output $apk +} finally { $env:JAVA_HOME = $previousJavaHome } diff --git a/tools/viture/viture-v2-driver-check/src/com/droiddeck/viturev2check/MainActivity.java b/tools/viture/viture-v2-driver-check/src/com/droiddeck/viturev2check/MainActivity.java new file mode 100644 index 0000000000..d5e639c6af --- /dev/null +++ b/tools/viture/viture-v2-driver-check/src/com/droiddeck/viturev2check/MainActivity.java @@ -0,0 +1,317 @@ +package com.droiddeck.viturev2check; + +import android.app.Activity; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.hardware.usb.UsbDevice; +import android.hardware.usb.UsbManager; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.SystemClock; +import android.util.Base64; +import android.util.Log; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; +import com.droiddeck.launcher.glasses.VitureV2Link; +import java.io.BufferedWriter; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import org.json.JSONArray; +import org.json.JSONObject; + +public final class MainActivity extends Activity { + private static final String PERMISSION = "com.droiddeck.viturev2check.USB_PERMISSION"; + private static final int VENDOR = 0x35ca, PRODUCT = 0x1301, INTERNAL_IMU = 0x0015; + private static final long TOTAL_LIMIT_MS = 25000, CLOSE_RESERVE_MS = 1500; + private final Handler handler = new Handler(Looper.getMainLooper()); + private final AtomicBoolean finishing = new AtomicBoolean(); + private final AtomicLong poses = new AtomicLong(), capturePoses = new AtomicLong(), packetBytes = new AtomicLong(); + private final AtomicLong readyCallbacks = new AtomicLong(), trackingOn = new AtomicLong(), trackingOff = new AtomicLong(), errors = new AtomicLong(); + private final Object poseLock = new Object(); + private UsbManager manager; + private UsbDevice pending; + private TextView status; + private VitureV2Link link; + private Journal journal; + private boolean busy, bootstrapHandled, firstOffAccepted, resumeAccepted, finalOffAccepted; + private int seconds; + private volatile String phase = "idle"; + private long startedMs, firstOffExtra = -1, finalOffExtra = -1, captureStartedNs, captureEndedNs; + private long firstCaptureTimeNs, lastCaptureTimeNs; + private float[] lastPose; + + private final BroadcastReceiver receiver = new BroadcastReceiver() { + @Override public void onReceive(Context context, Intent intent) { + if (!PERMISSION.equals(intent.getAction()) || pending == null) return; + UsbDevice device = pending; + pending = null; + if (manager.hasPermission(device)) begin(device); + else { busy = false; show("USB permission denied."); } + } + }; + + private final VitureV2Link.Listener listener = new VitureV2Link.Listener() { + @Override public void onReady() { + readyCallbacks.incrementAndGet(); + event("ready", "phase", phase); + handler.post(() -> bootstrapOff()); + } + @Override public void onValue(int message, int value) { event("value", "messageId", message, "value", value); } + @Override public void onPose(byte[] raw, float[] q, long timeNs) { + long count = poses.incrementAndGet(); + packetBytes.addAndGet(raw.length); + String observedPhase = phase; + synchronized (poseLock) { + lastPose = q.clone(); + if ("capture".equals(observedPhase)) { + if (capturePoses.incrementAndGet() == 1) firstCaptureTimeNs = timeNs; + lastCaptureTimeNs = timeNs; + } + } + event("pose", "phase", observedPhase, "count", count, "receiptTimeNs", timeNs, + "sharedXyzw", floats(q), "packetLength", raw.length, "packetBase64", Base64.encodeToString(raw, Base64.NO_WRAP)); + } + @Override public void onTracking(boolean active) { + if (active) trackingOn.incrementAndGet(); else trackingOff.incrementAndGet(); + event("tracking", "active", active, "phase", phase); + } + @Override public void onLost() { + errors.incrementAndGet(); + event("lost", "phase", phase); + handler.post(() -> finishCheck("driver_lost")); + } + }; + + @Override public void onCreate(Bundle saved) { + super.onCreate(saved); + manager = (UsbManager) getSystemService(USB_SERVICE); + seconds = Math.max(10, Math.min(15, getIntent().getIntExtra("seconds", 12))); + getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + LinearLayout layout = new LinearLayout(this); + layout.setOrientation(LinearLayout.VERTICAL); + layout.setPadding(24, 24, 24, 24); + Button start = new Button(this); + start.setText("Check production driver on Pro 2"); + start.setOnClickListener(view -> select()); + layout.addView(start); + Button stop = new Button(this); + stop.setText("Stop and close driver"); + stop.setOnClickListener(view -> finishCheck("user_stop")); + layout.addView(stop); + status = new TextView(this); + status.setTextIsSelectable(true); + ScrollView scroll = new ScrollView(this); + scroll.addView(status); + layout.addView(scroll); + setContentView(layout); + if (Build.VERSION.SDK_INT >= 33) registerReceiver(receiver, new IntentFilter(PERMISSION), Context.RECEIVER_NOT_EXPORTED); + else registerReceiver(receiver, new IntentFilter(PERMISSION)); + show("Actual compiled production VitureV2Link. Pro 2 only. Ready, pause 500 ms, capture " + seconds + " s, pause 500 ms, close."); + show("Logs: " + getFilesDir() + "/checks"); + if (getIntent().getBooleanExtra("auto", false)) select(); + } + + @Override protected void onDestroy() { + finishCheck("activity_destroyed"); + unregisterReceiver(receiver); + super.onDestroy(); + } + + private void select() { + if (busy || finishing.get()) { show("A check is already active or complete; reopen the activity for another run."); return; } + List matches = new ArrayList<>(); + for (UsbDevice device : manager.getDeviceList().values()) { + if (device.getVendorId() == VENDOR && device.getProductId() == PRODUCT) matches.add(device); + } + if (matches.size() != 1) { show("Expected exactly one 35ca:1301 Pro 2; found " + matches.size()); return; } + busy = true; + UsbDevice device = matches.get(0); + if (manager.hasPermission(device)) begin(device); + else { + pending = device; + manager.requestPermission(device, PendingIntent.getBroadcast(this, PRODUCT, + new Intent(PERMISSION).setPackage(getPackageName()), PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT)); + } + } + + private void begin(UsbDevice device) { + if (finishing.get()) return; + startedMs = SystemClock.elapsedRealtime(); + try { + File directory = new File(getFilesDir(), "checks"); + if (!directory.isDirectory() && !directory.mkdirs()) throw new IllegalStateException("Could not create log directory"); + File file = new File(directory, "driver-check-" + System.currentTimeMillis() + ".jsonl"); + journal = new Journal(file); + event("session", "vendorId", VENDOR, "productId", PRODUCT, "captureSeconds", seconds, + "totalLimitMillis", TOTAL_LIMIT_MS, "runtime", new JSONObject(readAsset("runtime-manifest.json"))); + show("Recording " + file.getAbsolutePath()); + phase = "bootstrap"; + handler.postDelayed(() -> finishCheck("watchdog"), TOTAL_LIMIT_MS - CLOSE_RESERVE_MS); + link = VitureV2Link.Companion.open(manager, device, listener); + event("open_returned", "opened", link != null); + if (link == null) { errors.incrementAndGet(); finishCheck("open_failed"); } + } catch (Exception error) { + errors.incrementAndGet(); + event("error", "operation", "open", "message", error.toString()); + finishCheck("open_error"); + } + } + + private void bootstrapOff() { + if (finishing.get() || bootstrapHandled) return; + if (link == null) { handler.postDelayed(() -> bootstrapOff(), 5); return; } + bootstrapHandled = true; + try { + firstOffAccepted = link.send(INTERNAL_IMU, new byte[] {0}); + long baseline = poses.get(); + phase = "bootstrap_off"; + event("off_requested", "stage", "bootstrap", "accepted", firstOffAccepted, "poseBaseline", baseline); + if (!firstOffAccepted) { errors.incrementAndGet(); finishCheck("bootstrap_off_rejected"); return; } + handler.postDelayed(() -> { + if (finishing.get()) return; + firstOffExtra = poses.get() - baseline; + event("off_observation", "stage", "bootstrap", "windowMillis", 500, "newPoses", firstOffExtra, + "trackingActive", link.getTrackingActive(), "ready", link.getReady()); + if (firstOffExtra != 0 || link.getTrackingActive()) errors.incrementAndGet(); + resume(); + }, 500); + } catch (Exception error) { fail("bootstrap_off", error); } + } + + private void resume() { + try { + phase = "capture"; + captureStartedNs = System.nanoTime(); + resumeAccepted = link.send(INTERNAL_IMU, new byte[] {1}); + event("on_requested", "accepted", resumeAccepted); + if (!resumeAccepted) { errors.incrementAndGet(); finishCheck("resume_rejected"); return; } + show("Capturing production-driver poses for " + seconds + " seconds."); + handler.postDelayed(() -> finalOff(), seconds * 1000L); + } catch (Exception error) { fail("resume", error); } + } + + private void finalOff() { + if (finishing.get()) return; + try { + finalOffAccepted = link.send(INTERNAL_IMU, new byte[] {0}); + captureEndedNs = System.nanoTime(); + long baseline = poses.get(); + phase = "final_off"; + event("off_requested", "stage", "final", "accepted", finalOffAccepted, "poseBaseline", baseline); + if (!finalOffAccepted) { errors.incrementAndGet(); finishCheck("final_off_rejected"); return; } + handler.postDelayed(() -> { + if (finishing.get()) return; + finalOffExtra = poses.get() - baseline; + event("off_observation", "stage", "final", "windowMillis", 500, "newPoses", finalOffExtra, + "trackingActive", link.getTrackingActive(), "ready", link.getReady()); + if (finalOffExtra != 0 || link.getTrackingActive()) errors.incrementAndGet(); + finishCheck("completed"); + }, 500); + } catch (Exception error) { fail("final_off", error); } + } + + private void fail(String operation, Exception error) { + errors.incrementAndGet(); + event("error", "operation", operation, "message", error.toString()); + finishCheck(operation + "_error"); + } + + private void finishCheck(String reason) { + if (!busy || !finishing.compareAndSet(false, true)) return; + pending = null; + handler.removeCallbacksAndMessages(null); + phase = "closing"; + long badFrames = 0; + try { + if (link != null) { badFrames = link.getBadFrames(); link.close(); } + } catch (Exception error) { + errors.incrementAndGet(); + event("error", "operation", "close", "message", error.toString()); + } finally { + phase = "closed"; + long captureCount = capturePoses.get(); + long captureNs = captureEndedNs > captureStartedNs ? captureEndedNs - captureStartedNs : 0; + double rate = 0; + JSONArray finalQ; + synchronized (poseLock) { + if (captureCount > 1 && lastCaptureTimeNs > firstCaptureTimeNs) + rate = (captureCount - 1) * 1_000_000_000.0 / (lastCaptureTimeNs - firstCaptureTimeNs); + finalQ = floats(lastPose); + } + boolean pass = "completed".equals(reason) && errors.get() == 0 && readyCallbacks.get() > 0 && + firstOffAccepted && resumeAccepted && finalOffAccepted && firstOffExtra == 0 && finalOffExtra == 0 && captureCount > 0 && + trackingOn.get() >= 2 && trackingOff.get() >= 2 && link != null && !link.getReady() && !link.getTrackingActive(); + event("summary", "reason", reason, "pass", pass, "totalMillis", SystemClock.elapsedRealtime() - startedMs, + "poseCount", poses.get(), "capturePoseCount", captureCount, "captureMillis", captureNs / 1_000_000.0, + "sampleRateHz", rate, "readyCallbacks", readyCallbacks.get(), "trackingOnCallbacks", trackingOn.get(), + "trackingOffCallbacks", trackingOff.get(), "errors", errors.get(), "badFrames", badFrames, + "bootstrapOffNewPoses", firstOffExtra, "finalOffNewPoses", finalOffExtra, + "readyAfterClose", link != null && link.getReady(), "trackingAfterClose", link != null && link.getTrackingActive(), + "lastSharedXyzw", finalQ, "packetBytes", packetBytes.get()); + if (journal != null) { + try { journal.close(); } catch (Exception error) { Log.e("VitureV2Check", "Log close failed", error); } + } + busy = false; + show("Finished: " + reason + ", pass=" + pass + ", capture poses=" + captureCount + ", rate=" + String.format(java.util.Locale.ROOT, "%.1f", rate) + " Hz."); + } + } + + private void event(String type, Object... fields) { + Journal output = journal; + if (output == null) return; + try { output.event(type, fields); } + catch (Exception error) { errors.incrementAndGet(); Log.e("VitureV2Check", "Could not log " + type, error); } + } + + private String readAsset(String name) throws Exception { + try (InputStream input = getAssets().open(name); ByteArrayOutputStream output = new ByteArrayOutputStream()) { + byte[] buffer = new byte[4096]; + for (int count; (count = input.read(buffer)) != -1;) output.write(buffer, 0, count); + return new String(output.toByteArray(), StandardCharsets.UTF_8); + } + } + + private static JSONArray floats(float[] values) { + JSONArray result = new JSONArray(); + if (values != null) for (float value : values) { + try { result.put((double) value); } catch (Exception ignored) { result.put(JSONObject.NULL); } + } + return result; + } + + private void show(String message) { + Log.i("VitureV2Check", message); + runOnUiThread(() -> status.append(message + "\n")); + } + + private static final class Journal implements AutoCloseable { + private final BufferedWriter writer; + Journal(File file) throws Exception { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)); } + synchronized void event(String type, Object... fields) throws Exception { + JSONObject json = new JSONObject(); + json.put("event", type); + json.put("elapsedRealtimeNanos", SystemClock.elapsedRealtimeNanos()); + for (int i = 0; i < fields.length; i += 2) json.put((String) fields[i], fields[i + 1]); + writer.write(json.toString()); + writer.newLine(); + writer.flush(); + } + @Override public synchronized void close() throws Exception { writer.close(); } + } +} diff --git a/tools/viture/viture-v2-probe/.gitignore b/tools/viture/viture-v2-probe/.gitignore new file mode 100644 index 0000000000..89f9ac04aa --- /dev/null +++ b/tools/viture/viture-v2-probe/.gitignore @@ -0,0 +1 @@ +out/ diff --git a/tools/viture/viture-v2-probe/AndroidManifest.xml b/tools/viture/viture-v2-probe/AndroidManifest.xml new file mode 100644 index 0000000000..422546fb9b --- /dev/null +++ b/tools/viture/viture-v2-probe/AndroidManifest.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/tools/viture/viture-v2-probe/LICENSE.upstream b/tools/viture/viture-v2-probe/LICENSE.upstream new file mode 100644 index 0000000000..9c1d9de29a --- /dev/null +++ b/tools/viture/viture-v2-probe/LICENSE.upstream @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Holger Bartnick + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/viture/viture-v2-probe/PROVENANCE.md b/tools/viture/viture-v2-probe/PROVENANCE.md new file mode 100644 index 0000000000..217439944a --- /dev/null +++ b/tools/viture/viture-v2-probe/PROVENANCE.md @@ -0,0 +1,77 @@ +# SDK-free Android VITURE Pro 2 probe + +Protocol and the pose test vector are adapted from Holger Bartnick's MIT-licensed +[elasticjava/viture-v2](https://github.com/elasticjava/viture-v2), pinned to commit +`ece8c30485f7d357fefa362ae74f3eabac9b3899`. Consult `LICENSE.upstream` for its license; +the APK also includes this notice at `assets/LICENSE.upstream`. +Sources consulted: upstream `PROTOCOL.md`, runtime `src/lib.rs` and `src/usbfs.rs`. +The upstream document says its protocol was derived from official SDK USB captures +and then verified using an independent implementation. This is third-party +SDK-derived protocol documentation, not a claim of clean-room discovery. + +This standalone Java application uses Android's USB host APIs. It includes no +vendor SDK, vendor native library, project Kotlin source, or project SDK trace. +The prior local SDK capture directories and downloaded vendor SDK were excluded +from this work. Its build uses the Java sources and manifest in this directory. + +Only VITURE Pro 2 `35ca:1301` (decimal PID 4865), interface 0, is accepted. The +active interface must be HID alternate 0 with exactly two endpoints: one 64-byte +interrupt IN and one 64-byte interrupt OUT. Endpoint addresses come from the +device descriptors. Standard GET_CONFIGURATION and GET_INTERFACE reads identify +the current transport; the probe changes neither setting. The input request is +queued before any protocol command. + +The probe queries firmware with `0x3003`, enables either pose at 120 Hz +(`0x0301 [1,2]`) or raw at 120 Hz (`0x0301 [2,2]`), and sends stream off +(`0x0301 [0,0]`) in `finally`. It does not query serial numbers or change display, +brightness, volume, film, or calibration settings. Pose and raw are separate modes. + +Every input completion retains its actual byte count and base64 bytes. Decoding +requires the v2 preamble, bounded declared length, byte-sum checksum, and exact +known event payload size. Pose requires finite quaternion components and norm +within 0.05 of 1. Raw samples require finite gyro/acceleration components; +acceleration norm is logged without assuming that moving hardware has a 1 g +reading. Valid frame, pose, raw, malformed frame, and malformed sample counters +remain separate. Device tick units are unknown. Transport completion is not a +firmware ACK; control ACKs are logged independently. + +Stream off is attempted on orderly completion, stop, activity destruction, and +caught errors after a stream-enable attempt. Input reads remain active for a +bounded off-response grace period before cancellation. Resource closing does not +depend on successful logging. Process termination, unplugging, or power loss can +prevent cleanup. + +Build with `./tools/viture/viture-v2-probe/build.ps1`. SDK discovery uses +`ANDROID_HOME`, `ANDROID_SDK_ROOT`, then `%LOCALAPPDATA%\Android\Sdk`. JDK discovery +uses `JAVA_HOME`, the optional `%USERPROFILE%\.jdks\jbr-17.0.9`, then `javac.exe` on +PATH. Explicit `-Sdk` and `-Java` override discovery. Thirteen protocol checks run +before APK compilation and signing. The APK is written to +`tools/viture/viture-v2-probe/out/viture-v2-probe-debug.apk` and uses the repository +test key. No Gradle dependency or vendor library is required. + +After installation, launch the default pose capture: + +```powershell +adb shell am start -n com.droiddeck.viturev2probe/.MainActivity --ez auto true --ei seconds 15 +``` + +For raw gyro and accelerometer data, pass `--es mode raw`: + +```powershell +adb shell am start -n com.droiddeck.viturev2probe/.MainActivity --ez auto true --es mode raw --ei seconds 15 +``` + +`mode` accepts `pose` or `raw` and defaults to `pose`. Automatic launch defaults to +PID 4865 and interface 0; if supplied, `--ei pid` and `--ei interface` must match +those exact values. `seconds` defaults to 15 and is clamped to 1..30. Descriptor +reads and bounded cleanup add a few seconds around that capture window. Allow +the USB permission dialog once. The UI provides a Pro 2 capture button using the +selected mode and a stop button. + +Logs are app-private JSONL files under +`/data/user/0/com.droiddeck.viturev2probe/files/captures/` named +`probe--pid-4865-if-0.jsonl`. +Use `adb shell run-as com.droiddeck.viturev2probe ls files/captures` to enumerate them +and `adb exec-out run-as com.droiddeck.viturev2probe cat files/captures/` to read. +For another launch with new extras, finish the existing activity or force-stop only +after `session_end` is present so the stream-off cleanup can complete. diff --git a/tools/viture/viture-v2-probe/assets/LICENSE.upstream b/tools/viture/viture-v2-probe/assets/LICENSE.upstream new file mode 100644 index 0000000000..9c1d9de29a --- /dev/null +++ b/tools/viture/viture-v2-probe/assets/LICENSE.upstream @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Holger Bartnick + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/viture/viture-v2-probe/build.ps1 b/tools/viture/viture-v2-probe/build.ps1 new file mode 100644 index 0000000000..d3fa85e05e --- /dev/null +++ b/tools/viture/viture-v2-probe/build.ps1 @@ -0,0 +1,61 @@ +param( + [string]$Sdk, + [string]$Java = $env:JAVA_HOME +) +$ErrorActionPreference = 'Stop' +if (-not $Sdk) { + if ($env:ANDROID_HOME) { $Sdk = $env:ANDROID_HOME } + elseif ($env:ANDROID_SDK_ROOT) { $Sdk = $env:ANDROID_SDK_ROOT } + elseif ($env:LOCALAPPDATA) { $Sdk = Join-Path $env:LOCALAPPDATA 'Android\Sdk' } + else { throw 'Set ANDROID_HOME / ANDROID_SDK_ROOT or pass -Sdk.' } +} +if (-not $Java) { + $fallbackJdk = Join-Path $env:USERPROFILE '.jdks\jbr-17.0.9' + $javacCommand = Get-Command javac.exe -ErrorAction SilentlyContinue + if (Test-Path -LiteralPath (Join-Path $fallbackJdk 'bin\javac.exe')) { $Java = $fallbackJdk } + elseif ($javacCommand) { $Java = Split-Path (Split-Path $javacCommand.Source -Parent) -Parent } +} +if (-not $Java -or -not (Test-Path -LiteralPath (Join-Path $Java 'bin\javac.exe'))) { + throw 'Set JAVA_HOME or pass -Java with a JDK containing bin\javac.exe.' +} +$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..\..')) +$output = Join-Path $PSScriptRoot 'out' +$classes = Join-Path $output ('classes-' + [Guid]::NewGuid().ToString('N')) +$testClasses = Join-Path $output ('tests-' + [Guid]::NewGuid().ToString('N')) +$dex = Join-Path $output ('dex-' + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Force -Path $output, $classes, $testClasses, $dex | Out-Null +$buildTools = Join-Path $Sdk 'build-tools\36.0.0' +$androidJar = Join-Path $Sdk 'platforms\android-34\android.jar' +$unsigned = Join-Path $output 'viture-v2-probe-unsigned.apk' +$aligned = Join-Path $output 'viture-v2-probe-aligned.apk' +$apk = Join-Path $output 'viture-v2-probe-debug.apk' +$classJar = Join-Path $output 'classes.jar' +$source = Join-Path $PSScriptRoot 'src\com\droiddeck\viturev2probe' +$previousJavaHome = $env:JAVA_HOME +try { + $env:JAVA_HOME = $Java + & (Join-Path $Java 'bin\javac.exe') --release 8 -encoding UTF-8 -d $testClasses (Join-Path $source 'Protocol.java') (Join-Path $PSScriptRoot 'tests\com\droiddeck\viturev2probe\ProtocolTest.java') + if ($LASTEXITCODE -ne 0) { throw 'test compilation failed' } + & (Join-Path $Java 'bin\java.exe') -cp $testClasses com.droiddeck.viturev2probe.ProtocolTest + if ($LASTEXITCODE -ne 0) { throw 'protocol tests failed' } + & (Join-Path $Java 'bin\javac.exe') --release 8 -classpath $androidJar -encoding UTF-8 -d $classes (Join-Path $source 'Protocol.java') (Join-Path $source 'MainActivity.java') + if ($LASTEXITCODE -ne 0) { throw 'javac failed' } + & (Join-Path $Java 'bin\jar.exe') cf $classJar -C $classes . + if ($LASTEXITCODE -ne 0) { throw 'jar failed' } + & (Join-Path $buildTools 'd8.bat') --min-api 26 --lib $androidJar --output $dex $classJar + if ($LASTEXITCODE -ne 0) { throw 'd8 failed' } + & (Join-Path $buildTools 'aapt2.exe') link --manifest (Join-Path $PSScriptRoot 'AndroidManifest.xml') -A (Join-Path $PSScriptRoot 'assets') -I $androidJar -o $unsigned --min-sdk-version 26 --target-sdk-version 34 + if ($LASTEXITCODE -ne 0) { throw 'aapt2 failed' } + & (Join-Path $Java 'bin\jar.exe') uf $unsigned -C $dex classes.dex + if ($LASTEXITCODE -ne 0) { throw 'APK dex insertion failed' } + & (Join-Path $buildTools 'zipalign.exe') -f 4 $unsigned $aligned + if ($LASTEXITCODE -ne 0) { throw 'zipalign failed' } + & (Join-Path $buildTools 'apksigner.bat') sign --ks (Join-Path $repo 'keystore\testkey.p12') --ks-key-alias testkey --ks-pass pass:android --key-pass pass:android --out $apk $aligned + if ($LASTEXITCODE -ne 0) { throw 'APK signing failed' } + & (Join-Path $buildTools 'apksigner.bat') verify --verbose $apk + if ($LASTEXITCODE -ne 0) { throw 'APK verification failed' } + Get-FileHash -Algorithm SHA256 -LiteralPath $apk + Write-Output $apk +} finally { + $env:JAVA_HOME = $previousJavaHome +} diff --git a/tools/viture/viture-v2-probe/src/com/droiddeck/viturev2probe/MainActivity.java b/tools/viture/viture-v2-probe/src/com/droiddeck/viturev2probe/MainActivity.java new file mode 100644 index 0000000000..4bcf40ccd8 --- /dev/null +++ b/tools/viture/viture-v2-probe/src/com/droiddeck/viturev2probe/MainActivity.java @@ -0,0 +1,451 @@ +package com.droiddeck.viturev2probe; + +import android.app.Activity; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.hardware.usb.UsbConfiguration; +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.os.Build; +import android.os.Bundle; +import android.os.SystemClock; +import android.util.Base64; +import android.util.Log; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; +import org.json.JSONArray; +import org.json.JSONObject; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeoutException; + +public final class MainActivity extends Activity { + private static final String PERMISSION = "com.droiddeck.viturev2probe.USB_PERMISSION"; + private static final int VENDOR = 0x35ca; + private static final int PRODUCT = 0x1301; + private static final int INTERFACE = 0; + private static final int BYTE_LIMIT = 4 * 1024 * 1024; + private UsbManager manager; + private TextView status; + private volatile boolean stop; + private boolean busy; + private UsbDevice pending; + private int durationSeconds = 15; + private boolean rawMode; + private boolean invalidMode; + + private final BroadcastReceiver receiver = new BroadcastReceiver() { + @Override public void onReceive(Context context, Intent intent) { + if (!PERMISSION.equals(intent.getAction()) || pending == null) return; + UsbDevice device = pending; + pending = null; + if (manager.hasPermission(device)) start(device); + else { busy = false; show("USB permission denied."); } + } + }; + + @Override public void onCreate(Bundle saved) { + super.onCreate(saved); + manager = (UsbManager) getSystemService(USB_SERVICE); + getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + LinearLayout layout = new LinearLayout(this); + layout.setOrientation(LinearLayout.VERTICAL); + layout.setPadding(24, 24, 24, 24); + status = new TextView(this); + status.setTextIsSelectable(true); + addButton(layout, "Probe VITURE Pro 2", () -> select(PRODUCT, INTERFACE)); + addButton(layout, "Stop and disable stream", () -> stop = true); + ScrollView scroll = new ScrollView(this); + scroll.addView(status); + layout.addView(scroll); + setContentView(layout); + if (Build.VERSION.SDK_INT >= 33) registerReceiver(receiver, new IntentFilter(PERMISSION), Context.RECEIVER_NOT_EXPORTED); + else registerReceiver(receiver, new IntentFilter(PERMISSION)); + String mode = getIntent().getStringExtra("mode"); + rawMode = "raw".equals(mode); + invalidMode = mode != null && !rawMode && !"pose".equals(mode); + durationSeconds = Math.max(1, Math.min(30, getIntent().getIntExtra("seconds", 15))); + show("Pro 2 firmware query, " + (rawMode ? "raw" : "pose") + " at 120 Hz, then stream off. Capture window: " + durationSeconds + " s."); + if (invalidMode) show("Invalid mode: use pose or raw."); + show("Logs: " + getFilesDir() + "/captures"); + for (UsbDevice device : manager.getDeviceList().values()) { + if (device.getVendorId() == VENDOR && device.getProductId() == PRODUCT) + show(String.format("Attached Pro 2 %04x:%04x, %d interfaces", VENDOR, PRODUCT, device.getInterfaceCount())); + } + if (getIntent().getBooleanExtra("auto", false)) { + select(getIntent().getIntExtra("pid", PRODUCT), getIntent().getIntExtra("interface", INTERFACE)); + } + } + + private void addButton(LinearLayout layout, String label, Runnable action) { + Button button = new Button(this); + button.setText(label); + button.setOnClickListener(view -> action.run()); + layout.addView(button); + } + + @Override protected void onDestroy() { + stop = true; + unregisterReceiver(receiver); + super.onDestroy(); + } + + private void show(String message) { + Log.i("VitureV2Probe", message); + runOnUiThread(() -> status.append(message + "\n")); + } + + private void select(int product, int intf) { + if (busy) { show("A probe or permission request is already active."); return; } + if (invalidMode) { show("Probe disabled: use mode pose or raw."); return; } + if (product != PRODUCT || intf != INTERFACE) { + show("This probe requires Pro 2 pid 4865 (0x1301), interface 0."); return; + } + List matches = new ArrayList<>(); + for (UsbDevice device : manager.getDeviceList().values()) { + if (device.getVendorId() == VENDOR && device.getProductId() == product) matches.add(device); + } + if (matches.size() != 1) { show("Expected one matching device; found " + matches.size()); return; } + busy = true; + stop = false; + UsbDevice device = matches.get(0); + if (manager.hasPermission(device)) start(device); + else { + pending = device; + PendingIntent permission = PendingIntent.getBroadcast(this, product, + new Intent(PERMISSION).setPackage(getPackageName()), PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); + manager.requestPermission(device, permission); + } + } + + private void start(UsbDevice device) { + new Thread(() -> { + File directory = new File(getFilesDir(), "captures"); + directory.mkdirs(); + File file = new File(directory, "probe-" + System.currentTimeMillis() + "-pid-" + device.getProductId() + "-if-" + INTERFACE + ".jsonl"); + try (Journal journal = new Journal(file)) { + show("Recording " + file.getName()); + journal.event("session", "vendorId", device.getVendorId(), "productId", device.getProductId(), + "interface", INTERFACE, "seconds", durationSeconds, "wallTimeMillis", System.currentTimeMillis(), + "mode", rawMode ? "raw" : "pose", + "modeSource", getIntent().hasExtra("mode") ? "explicit intent extra" : "default pose", + "requestedStream", rawMode ? "raw_120hz" : "pose_120hz", + "upstreamCommit", "ece8c30485f7d357fefa362ae74f3eabac9b3899", "byteLimitPerInput", BYTE_LIMIT, + "quaternionNormTolerance", 0.05, "timestampMeaning", "host elapsedRealtimeNanos; decoded tick is an uncalibrated device field"); + describe(device, journal); + probe(device, journal); + journal.event("session_end", "stoppedByUserOrActivity", stop); + show("Saved " + file.getAbsolutePath()); + } catch (Exception error) { show("Probe error: " + error); } + finally { runOnUiThread(() -> busy = false); } + }, "viture-v2-probe").start(); + } + + private void describe(UsbDevice device, Journal journal) throws Exception { + journal.event("device", "vendorId", device.getVendorId(), "productId", device.getProductId(), "configurationCount", device.getConfigurationCount()); + for (int c = 0; c < device.getConfigurationCount(); c++) { + UsbConfiguration configuration = device.getConfiguration(c); + journal.event("configuration", "productId", device.getProductId(), "id", configuration.getId(), "interfaceCount", configuration.getInterfaceCount()); + for (int i = 0; i < configuration.getInterfaceCount(); i++) { + UsbInterface intf = configuration.getInterface(i); + journal.event("interface", "productId", device.getProductId(), "configurationId", configuration.getId(), + "interface", intf.getId(), "alternate", intf.getAlternateSetting(), "class", intf.getInterfaceClass(), + "subclass", intf.getInterfaceSubclass(), "protocol", intf.getInterfaceProtocol()); + for (int e = 0; e < intf.getEndpointCount(); e++) { + UsbEndpoint endpoint = intf.getEndpoint(e); + journal.event("endpoint", "productId", device.getProductId(), "configurationId", configuration.getId(), + "interface", intf.getId(), "alternate", intf.getAlternateSetting(), "address", endpoint.getAddress(), + "type", endpoint.getType(), "direction", endpoint.getDirection(), "maxPacketSize", endpoint.getMaxPacketSize(), "interval", endpoint.getInterval()); + } + } + } + } + + private void probe(UsbDevice device, Journal journal) throws Exception { + if (device.getVendorId() != VENDOR || device.getProductId() != PRODUCT) { + journal.event("outcome", "result", "unsupported_product"); return; + } + UsbDeviceConnection connection = manager.openDevice(device); + if (connection == null) { journal.event("outcome", "result", "open_failed"); return; } + UsbInterface claimed = null; + Pump pump = new Pump(connection, journal); + UsbEndpoint output = null; + boolean readsReady = false; + boolean enableAttempted = false; + String result = "unsupported_transport"; + try { + byte[] descriptors = connection.getRawDescriptors(); + journal.event("raw_descriptors", "length", descriptors == null ? -1 : descriptors.length, "bytesBase64", encode(descriptors)); + byte[] active = new byte[1]; + int configRead = connection.controlTransfer(0x80, 8, 0, 0, active, 1, 500); + journal.event("get_configuration", "result", configRead, "configuration", configRead == 1 ? active[0] & 255 : -1); + if (configRead != 1) return; + UsbConfiguration configuration = null; + for (int c = 0; c < device.getConfigurationCount(); c++) { + if (device.getConfiguration(c).getId() == (active[0] & 255)) configuration = device.getConfiguration(c); + } + if (configuration == null) return; + List alternatives = new ArrayList<>(); + for (int i = 0; i < configuration.getInterfaceCount(); i++) { + if (configuration.getInterface(i).getId() == INTERFACE) alternatives.add(configuration.getInterface(i)); + } + byte[] alt = new byte[1]; + int altRead = connection.controlTransfer(0x81, 10, 0, INTERFACE, alt, 1, 500); + int activeAlt = altRead == 1 ? alt[0] & 255 : alternatives.size() == 1 && alternatives.get(0).getAlternateSetting() == 0 ? 0 : -1; + journal.event("get_interface", "result", altRead, "alternate", activeAlt, + "evidence", altRead == 1 ? "GET_INTERFACE" : "only advertised alternate zero or unknown"); + UsbInterface selected = null; + for (UsbInterface intf : alternatives) if (intf.getAlternateSetting() == activeAlt) selected = intf; + if (selected == null) { journal.event("unsupported", "reason", "selected active interface unavailable"); return; } + if (activeAlt != 0 || selected.getInterfaceClass() != UsbConstants.USB_CLASS_HID || selected.getEndpointCount() != 2) { + journal.event("unsupported", "reason", "Pro 2 requires active HID interface 0 alternate 0 with two endpoints"); return; + } + List ins = new ArrayList<>(); + int outputs = 0; + for (int e = 0; e < selected.getEndpointCount(); e++) { + UsbEndpoint endpoint = selected.getEndpoint(e); + if (endpoint.getType() != UsbConstants.USB_ENDPOINT_XFER_INT || endpoint.getMaxPacketSize() != 64) continue; + if (endpoint.getDirection() == UsbConstants.USB_DIR_IN) ins.add(endpoint); + else { output = endpoint; outputs++; } + } + if (outputs != 1 || ins.size() != 1) { + output = null; + journal.event("unsupported", "reason", "requires exactly one 64-byte interrupt IN and one 64-byte interrupt OUT", + "eligibleInputs", ins.size(), "eligibleOutputs", outputs); + return; + } + boolean success = connection.claimInterface(selected, false); + journal.event("claim_interface", "force", false, "success", success); + if (!success) { + success = connection.claimInterface(selected, true); + journal.event("claim_interface", "force", true, "success", success); + } + if (!success) { output = null; result = "claim_failed"; return; } + claimed = selected; + for (UsbEndpoint endpoint : ins) { + Input input = new Input(endpoint); + if (!input.request.initialize(connection, endpoint)) { input.request.close(); result = "input_initialize_failed"; return; } + input.request.setClientData(input); + pump.inputs.add(input); + } + readsReady = true; + for (Input input : pump.inputs) readsReady &= pump.queue(input); + journal.event("inputs_started", "allQueued", readsReady, "inputCount", pump.inputs.size(), "outputEndpoint", output.getAddress()); + if (!readsReady || stop) { result = "input_queue_failed_or_stopped"; return; } + long deadline = SystemClock.elapsedRealtime() + durationSeconds * 1000L; + pump.send(output, "firmware_query", Protocol.firmware()); + pump.until(Math.min(deadline, SystemClock.elapsedRealtime() + 400), true, true); + if (!stop && SystemClock.elapsedRealtime() < deadline) { + enableAttempted = true; + pump.send(output, rawMode ? "raw_120hz_enable" : "pose_120hz_enable", rawMode ? Protocol.raw120() : Protocol.pose120()); + pump.until(deadline, true, true); + } + result = pump.validPose > 0 ? "validated_v2_pose" : pump.validRaw > 0 ? "validated_v2_raw" : pump.validFrames > 0 ? "v2_frames_without_validated_imu" : "no_validated_v2_frames"; + } catch (Exception error) { + result = "error"; + journal.event("error", "message", error.toString()); + } finally { + if (enableAttempted && claimed != null && output != null && readsReady) { + try { + for (Input input : pump.inputs) if (!input.pending && input.bytes < BYTE_LIMIT) pump.queue(input); + pump.send(output, "stream_off_finally", Protocol.off()); + pump.until(SystemClock.elapsedRealtime() + 200, false, true); + } catch (Exception error) { journal.safeEvent("stream_off_error", "message", error.toString()); } + } + try { + for (Input input : pump.inputs) if (input.pending) { + input.cancelRequested = true; + try { journal.safeEvent("input_cancel", "endpoint", input.endpoint.getAddress(), "success", input.request.cancel()); } + catch (Exception error) { journal.safeEvent("input_cancel_error", "message", error.toString()); } + } + for (Command command : pump.commands) if (command.pending) { + command.cancelRequested = true; + try { journal.safeEvent("command_cancel", "name", command.name, "success", command.request.cancel()); } + catch (Exception error) { journal.safeEvent("command_cancel_error", "message", error.toString()); } + } + try { pump.until(SystemClock.elapsedRealtime() + 100, false, false); } catch (Exception ignored) {} + for (Input input : pump.inputs) { + journal.safeEvent("input_end", "endpoint", input.endpoint.getAddress(), "bytes", input.bytes, "packets", input.packets, + "zeroLengthCompletions", input.zeros, "pendingAtClose", input.pending); + } + if (claimed != null) { + try { journal.safeEvent("release_interface", "success", connection.releaseInterface(claimed)); } + catch (Exception error) { journal.safeEvent("release_interface_error", "message", error.toString()); } + } + } finally { + try { connection.close(); } + finally { + for (Input input : pump.inputs) { + try { input.request.close(); } catch (Exception error) { journal.safeEvent("input_close_error", "message", error.toString()); } + } + for (Command command : pump.commands) { + try { command.request.close(); } catch (Exception error) { journal.safeEvent("command_close_error", "message", error.toString()); } + } + } + } + journal.safeEvent("outcome", "result", result, "validFrames", pump.validFrames, "invalidFrames", pump.invalidFrames, + "validPose", pump.validPose, "validRaw", pump.validRaw, "invalidSamples", pump.invalidSamples, + "firmwareReplies", pump.firmwareReplies, "successfulFirmwareReplies", pump.successfulFirmwareReplies, "controlAcks", pump.controlAcks, + "nonzeroControlStatuses", pump.nonzeroControlStatuses, "streamEnableAttempted", enableAttempted, + "poseEnableAttempted", !rawMode && enableAttempted, "rawEnableAttempted", rawMode && enableAttempted, + "streamOffWriteCompleted", pump.offCompleted); + show("Outcome: " + result + "; valid pose " + pump.validPose + ", raw " + pump.validRaw + ", v2 frames " + pump.validFrames); + } + } + + private final class Pump { + final UsbDeviceConnection connection; + final Journal journal; + final List inputs = new ArrayList<>(); + final List commands = new ArrayList<>(); + int validFrames, invalidFrames, validPose, validRaw, invalidSamples, firmwareReplies, successfulFirmwareReplies, controlAcks, nonzeroControlStatuses; + boolean offCompleted; + Pump(UsbDeviceConnection connection, Journal journal) { this.connection = connection; this.journal = journal; } + + boolean queue(Input input) throws Exception { + if (input.bytes >= BYTE_LIMIT) return false; + input.buffer.clear(); + input.buffer.limit(Math.min(input.buffer.capacity(), BYTE_LIMIT - input.bytes)); + input.cancelRequested = false; + input.queued = SystemClock.elapsedRealtimeNanos(); + input.pending = input.request.queue(input.buffer); + if (!input.pending) journal.event("input_queue_failed", "endpoint", input.endpoint.getAddress()); + return input.pending; + } + + void send(UsbEndpoint endpoint, String name, byte[] bytes) throws Exception { + Command command = new Command(name, bytes); + if (!command.request.initialize(connection, endpoint)) { command.request.close(); journal.event("command_initialize_failed", "name", name); return; } + command.request.setClientData(command); + commands.add(command); + command.pending = command.request.queue(command.buffer); + journal.event("command_queued", "name", name, "endpoint", endpoint.getAddress(), "length", bytes.length, + "bytesBase64", encode(bytes), "queued", command.pending); + long deadline = SystemClock.elapsedRealtime() + 400; + while (command.pending && SystemClock.elapsedRealtime() < deadline) step(50, true); + if (command.pending) { + command.cancelRequested = true; + journal.event("command_timeout", "name", name, "cancelled", command.request.cancel()); + } + } + + void until(long deadline, boolean respectStop, boolean requeueInputs) throws Exception { + while ((!respectStop || !stop) && SystemClock.elapsedRealtime() < deadline) { + step(Math.min(50, Math.max(1, deadline - SystemClock.elapsedRealtime())), requeueInputs); + } + } + + void step(long timeout, boolean requeue) throws Exception { + try { + UsbRequest completed = connection.requestWait(timeout); + if (completed == null) throw new IllegalStateException("requestWait returned null"); + Object data = completed.getClientData(); + if (data instanceof Command) { + Command command = (Command) data; + command.pending = false; + int length = command.buffer.position(); + if (command.name.equals("stream_off_finally") && length == command.length) offCompleted = true; + journal.event("command_completion", "name", command.name, "actualLength", length, "expectedLength", command.length, + "afterCancel", command.cancelRequested); + return; + } + Input input = (Input) data; + input.pending = false; + int count = input.buffer.position(); + byte[] bytes = new byte[count]; + input.buffer.flip(); + input.buffer.get(bytes); + input.bytes += count; + if (count > 0) input.packets++; else input.zeros++; + journal.event("input_transfer", "endpoint", input.endpoint.getAddress(), "queueElapsedRealtimeNanos", input.queued, + "length", count, "bytesBase64", encode(bytes), "afterCancel", input.cancelRequested); + if (count > 0) decode(bytes, input.endpoint.getAddress()); + if (requeue && input.bytes < BYTE_LIMIT) queue(input); + } catch (TimeoutException ignored) {} + } + + void decode(byte[] bytes, int endpoint) throws Exception { + Protocol.Frame frame; + try { frame = Protocol.parse(bytes); } + catch (IllegalArgumentException error) { invalidFrames++; journal.event("invalid_v2_frame", "endpoint", endpoint, "reason", error.getMessage()); return; } + validFrames++; + journal.event("v2_frame", "endpoint", endpoint, "messageId", frame.message, "payloadLength", frame.payload.length); + if (frame.message == Protocol.POSE || frame.message == Protocol.RAW) { + try { + Protocol.Sample sample = frame.message == Protocol.POSE ? Protocol.pose(frame) : Protocol.raw(frame); + if (frame.message == Protocol.POSE) validPose++; else validRaw++; + JSONArray values = new JSONArray(); + for (float value : sample.values) values.put((double) value); + journal.event(frame.message == Protocol.POSE ? "valid_pose" : "valid_raw", "endpoint", endpoint, + "tick", sample.tick, "values", values, "norm", sample.norm, + "fields", frame.message == Protocol.POSE ? "qw,qx,qy,qz" : "gyroX,gyroY,gyroZ,accelX,accelY,accelZ"); + } catch (IllegalArgumentException error) { invalidSamples++; journal.event("invalid_sample", "endpoint", endpoint, "messageId", frame.message, "reason", error.getMessage()); } + } else if (frame.message == Protocol.FIRMWARE + 0x2000 && frame.payload.length >= 1) { + firmwareReplies++; + String firmware = new String(frame.payload, 1, frame.payload.length - 1, StandardCharsets.US_ASCII).replace("\u0000", ""); + if (frame.payload[0] == 0 && !firmware.isEmpty() && firmware.matches("[ -~]+")) successfulFirmwareReplies++; + journal.event("firmware_reply", "endpoint", endpoint, "status", frame.payload[0] & 255, "firmware", firmware); + } else if (frame.message == Protocol.CONTROL + 0x2000 && frame.payload.length == 1) { + controlAcks++; + if (frame.payload[0] != 0) nonzeroControlStatuses++; + journal.event("control_ack", "endpoint", endpoint, "status", frame.payload[0] & 255); + } + } + } + + private static final class Input { + final UsbEndpoint endpoint; + final UsbRequest request = new UsbRequest(); + final ByteBuffer buffer; + boolean pending, cancelRequested; + int bytes, packets, zeros; + long queued; + Input(UsbEndpoint endpoint) { this.endpoint = endpoint; buffer = ByteBuffer.allocateDirect(Math.max(1, endpoint.getMaxPacketSize())); } + } + + private static final class Command { + final String name; + final int length; + final UsbRequest request = new UsbRequest(); + final ByteBuffer buffer; + boolean pending, cancelRequested; + Command(String name, byte[] bytes) { this.name = name; length = bytes.length; buffer = ByteBuffer.allocateDirect(length); buffer.put(bytes).flip(); } + } + + private static String encode(byte[] bytes) { return bytes == null ? "" : Base64.encodeToString(bytes, Base64.NO_WRAP); } + + private static final class Journal implements AutoCloseable { + final BufferedWriter writer; + Journal(File file) throws Exception { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)); } + void event(String event, Object... fields) throws Exception { + JSONObject json = new JSONObject(); + json.put("event", event); + json.put("elapsedRealtimeNanos", SystemClock.elapsedRealtimeNanos()); + for (int i = 0; i < fields.length; i += 2) json.put((String) fields[i], fields[i + 1]); + writer.write(json.toString()); + writer.newLine(); + writer.flush(); + } + void safeEvent(String event, Object... fields) { + try { event(event, fields); } catch (Exception error) { Log.e("VitureV2Probe", "Could not log " + event, error); } + } + @Override public void close() throws Exception { writer.close(); } + } +} diff --git a/tools/viture/viture-v2-probe/src/com/droiddeck/viturev2probe/Protocol.java b/tools/viture/viture-v2-probe/src/com/droiddeck/viturev2probe/Protocol.java new file mode 100644 index 0000000000..852ae858d0 --- /dev/null +++ b/tools/viture/viture-v2-probe/src/com/droiddeck/viturev2probe/Protocol.java @@ -0,0 +1,85 @@ +package com.droiddeck.viturev2probe; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Arrays; + +public final class Protocol { + public static final int FIRMWARE = 0x3003; + public static final int CONTROL = 0x0301; + public static final int POSE = 0x7308; + public static final int RAW = 0x7309; + + private Protocol() {} + + public static byte[] firmware() { return frame(FIRMWARE, new byte[0]); } + public static byte[] pose120() { return frame(CONTROL, new byte[] {1, 2}); } + public static byte[] raw120() { return frame(CONTROL, new byte[] {2, 2}); } + public static byte[] off() { return frame(CONTROL, new byte[] {0, 0}); } + + static byte[] frame(int message, byte[] payload) { + if (payload.length > 56) throw new IllegalArgumentException("payload exceeds upstream 64-byte frame"); + ByteBuffer buffer = ByteBuffer.allocate(8 + payload.length).order(ByteOrder.LITTLE_ENDIAN); + int sum = 0; + for (byte value : payload) sum = (sum + (value & 255)) & 65535; + buffer.putShort((short) 0x10).putShort((short) message).putShort((short) payload.length).putShort((short) sum).put(payload); + return buffer.array(); + } + + public static Frame parse(byte[] data) { + if (data.length < 8) throw new IllegalArgumentException("short_header"); + if (u16(data, 0) != 0x10) throw new IllegalArgumentException("preamble"); + int length = u16(data, 4); + if (length > 56 || length + 8 > data.length) throw new IllegalArgumentException("payload_length"); + int sum = 0; + for (int i = 8; i < 8 + length; i++) sum = (sum + (data[i] & 255)) & 65535; + if (sum != u16(data, 6)) throw new IllegalArgumentException("checksum"); + return new Frame(u16(data, 2), Arrays.copyOfRange(data, 8, 8 + length)); + } + + public static Sample pose(Frame frame) { + if (frame.message != POSE || frame.payload.length != 24) throw new IllegalArgumentException("pose_length_or_id"); + float[] values = floats(frame.payload, 8, 4); + double squared = 0; + for (float value : values) squared += (double) value * value; + double norm = Math.sqrt(squared); + if (Math.abs(norm - 1.0) > 0.05) throw new IllegalArgumentException("quaternion_norm"); + return new Sample(tick(frame.payload), values, norm); + } + + public static Sample raw(Frame frame) { + if (frame.message != RAW || frame.payload.length != 56) throw new IllegalArgumentException("raw_length_or_id"); + float[] values = floats(frame.payload, 10, 6); + double accelNorm = Math.sqrt((double) values[3] * values[3] + (double) values[4] * values[4] + (double) values[5] * values[5]); + return new Sample(tick(frame.payload), values, accelNorm); + } + + private static float[] floats(byte[] data, int offset, int count) { + ByteBuffer buffer = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN); + float[] values = new float[count]; + for (int i = 0; i < count; i++) { + values[i] = buffer.getFloat(offset + i * 4); + if (Float.isNaN(values[i]) || Float.isInfinite(values[i])) throw new IllegalArgumentException("non_finite"); + } + return values; + } + + private static long tick(byte[] payload) { + return ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).getInt(4) & 0xffffffffL; + } + + static int u16(byte[] data, int offset) { return (data[offset] & 255) | ((data[offset + 1] & 255) << 8); } + + public static final class Frame { + public final int message; + public final byte[] payload; + Frame(int message, byte[] payload) { this.message = message; this.payload = payload; } + } + + public static final class Sample { + public final long tick; + public final float[] values; + public final double norm; + Sample(long tick, float[] values, double norm) { this.tick = tick; this.values = values; this.norm = norm; } + } +} diff --git a/tools/viture/viture-v2-probe/tests/com/droiddeck/viturev2probe/ProtocolTest.java b/tools/viture/viture-v2-probe/tests/com/droiddeck/viturev2probe/ProtocolTest.java new file mode 100644 index 0000000000..117a1687d8 --- /dev/null +++ b/tools/viture/viture-v2-probe/tests/com/droiddeck/viturev2probe/ProtocolTest.java @@ -0,0 +1,48 @@ +package com.droiddeck.viturev2probe; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Arrays; + +public final class ProtocolTest { + private static int checks; + public static void main(String[] args) { + equal(Protocol.firmware(), hex("10 00 03 30 00 00 00 00")); + equal(Protocol.pose120(), hex("10 00 01 03 02 00 03 00 01 02")); + equal(Protocol.raw120(), hex("10 00 01 03 02 00 04 00 02 02")); + equal(Protocol.off(), hex("10 00 01 03 02 00 00 00 00 00")); + byte[] payload = hex("26 01 00 00 59 d6 21 00 dd e3 2b 3e 52 5d 7c 3f dd 45 9a 3b e8 27 52 3a"); + byte[] poseFrame = Protocol.frame(Protocol.POSE, payload); + Protocol.Sample sample = Protocol.pose(Protocol.parse(poseFrame)); + check(sample.tick == 0x0021d659L && Math.abs(sample.norm - 1) < 0.001); + check(Protocol.pose(Protocol.parse(Arrays.copyOf(poseFrame, 64))).tick == sample.tick); + reject(() -> Protocol.parse(Arrays.copyOf(poseFrame, 31))); + byte[] corrupt = poseFrame.clone(); + corrupt[8] ^= 1; + reject(() -> Protocol.parse(corrupt)); + reject(() -> Protocol.parse(hex("ff fe 00 00 00 00 00 00"))); + reject(() -> Protocol.pose(Protocol.parse(Protocol.frame(Protocol.POSE, new byte[24])))); + ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).putFloat(8, Float.NaN); + reject(() -> Protocol.pose(Protocol.parse(Protocol.frame(Protocol.POSE, payload)))); + byte[] raw = new byte[56]; + ByteBuffer buffer = ByteBuffer.wrap(raw).order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(4, -1).putFloat(10, 0.1f).putFloat(14, 0.2f).putFloat(18, 0.3f).putFloat(30, 1f); + Protocol.Sample rawSample = Protocol.raw(Protocol.parse(Protocol.frame(Protocol.RAW, raw))); + check(rawSample.tick == 0xffffffffL && rawSample.values[0] == 0.1f && rawSample.norm == 1); + buffer.putFloat(30, Float.POSITIVE_INFINITY); + reject(() -> Protocol.raw(Protocol.parse(Protocol.frame(Protocol.RAW, raw)))); + System.out.println("Protocol tests passed: " + checks); + } + private static void check(boolean condition) { if (!condition) throw new AssertionError(); checks++; } + private static void equal(byte[] actual, byte[] expected) { check(Arrays.equals(actual, expected)); } + private static void reject(Runnable operation) { + try { operation.run(); } catch (IllegalArgumentException expected) { checks++; return; } + throw new AssertionError("Expected rejection"); + } + private static byte[] hex(String text) { + String[] parts = text.split(" "); + byte[] result = new byte[parts.length]; + for (int i = 0; i < parts.length; i++) result[i] = (byte) Integer.parseInt(parts[i], 16); + return result; + } +}