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 280c2dabdb..b6f98878ee 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -1618,6 +1618,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, @@ -1683,6 +1684,9 @@ class MainActivity : ComponentActivity() { }, 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) @@ -1871,10 +1875,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 e7c3385d30..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() @@ -2012,7 +2047,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (drawerOpen) { if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) { if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { - drawerPage = sessionDrawerPages(SessionState.mode == SessionService.MODE_STEAM && secondScreenDisplays.isNotEmpty(), glasses.present) + drawerPage = sessionDrawerPages(secondScreenDisplays.isNotEmpty(), glasses.present) .step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) releaseDrawerDirection() } @@ -2456,6 +2491,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { applyUnfoldedControls() } + private fun chooseUnfoldedControlsWithController(on: Boolean) { + SessionPrefs.setUnfoldedControlsWithController(this, on) + unfoldedControlsWithController = on + applyUnfoldedControls() + } + private fun refreshControls() { applyUnfoldedControls() updateOnScreenControls() @@ -2465,11 +2506,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (!::sessionRoot.isInitialized) return val width = sessionRoot.width val height = sessionRoot.height - val wanted = unfoldedControls && com.droiddeck.launcher.session.SessionDisplay.foldable(this) && - !PadBridge.anyControllerConnected() && !SteamControllerBle.connected && - SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad && - !pipUi && !isInPictureInPictureMode && width > 0 && height > 0 && - resources.configuration.smallestScreenWidthDp >= com.droiddeck.launcher.session.SessionDisplay.UNFOLDED_MIN_DP + val wanted = com.droiddeck.launcher.session.SessionDisplay.unfoldedControlsWanted( + enabled = unfoldedControls, + foldable = com.droiddeck.launcher.session.SessionDisplay.foldable(this), + controllerConnected = PadBridge.anyControllerConnected() || SteamControllerBle.connected, + keepWithController = unfoldedControlsWithController, + steamDeckPad = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad, + pip = pipUi || isInPictureInPictureMode, + width = width, + height = height, + smallestWidthDp = resources.configuration.smallestScreenWidthDp, + ) val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height) else FrameLayout.LayoutParams.MATCH_PARENT val params = surfaceView.layoutParams as FrameLayout.LayoutParams @@ -2888,11 +2935,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { super.onStart() if (runtimeRemovalBlocked) return started = true + refreshActivityDisplayId() displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper())) refreshSecondScreenDisplays() if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode) startedScreens++ - SessionService.setActivityVisible(this, true, shownOnDisplayId) + SessionService.setActivityVisible(this, true, sessionActivityDisplayId) Glasses.rescan() updateGlassesScreen() updateHandCamera() @@ -2906,7 +2954,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { closeSecondScreen(reset = false) startedScreens = (startedScreens - 1).coerceAtLeast(0) updateGlassesScreen() - if (startedScreens == 0) SessionService.setActivityVisible(this, false) + if (startedScreens == 0) SessionService.setActivityVisible(this, false, sessionActivityDisplayId) super.onStop() } @@ -2937,6 +2985,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onResume() { super.onResume() + if (refreshActivityDisplayId() && started) { + SessionService.setActivityDisplay(this, sessionActivityDisplayId) + } applyFollowOrientation(resources.configuration) if (runtimeRemovalBlocked) return com.droiddeck.launcher.ui.Motion.refresh(this) @@ -3418,7 +3469,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun finishFlooded() { if (isFinishing) return - val signal = com.droiddeck.launcher.ui.Themes.byId(SessionPrefs.theme(this)).signal + val signal = com.droiddeck.launcher.ui.Themes.current(this).signal com.droiddeck.launcher.ui.QuitFlood.mark(signal.toArgb()) window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(signal.toArgb())) quitFlooded = true @@ -3449,7 +3500,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun completeLeave() { if (isFinishing) return - val signal = com.droiddeck.launcher.ui.Themes.byId(SessionPrefs.theme(this)).signal + val signal = com.droiddeck.launcher.ui.Themes.current(this).signal com.droiddeck.launcher.ui.QuitFlood.mark(signal.toArgb()) window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(signal.toArgb())) quitFlooded = true diff --git a/app/src/main/java/com/droiddeck/launcher/core/Downloader.java b/app/src/main/java/com/droiddeck/launcher/core/Downloader.java index 2527c57e82..183076188d 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/Downloader.java +++ b/app/src/main/java/com/droiddeck/launcher/core/Downloader.java @@ -54,7 +54,12 @@ public final class Downloader { java.util.function.Consumer progress) { if (expectedSha256 != null && !expectedSha256.matches("(?i)[0-9a-f]{64}")) throw new IllegalArgumentException("Expected SHA-256 must be 64 hex characters"); - return downloadCandidates(url, DownloadSource.INSTANCE.candidates(url), destination, resume, expectedSha256, progress); + return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, progress); + } + + /** A third-party mirror may only serve bytes that can be checked against a digest from a direct source. */ + static List sources(String url, String expectedSha256) { + return expectedSha256 == null ? java.util.Collections.singletonList(url) : DownloadSource.INSTANCE.candidates(url); } // Package-private for the local multi-source HTTP test. diff --git a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt index a667543a69..491101dba2 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt @@ -2,14 +2,51 @@ package com.droiddeck.launcher.core object LogRedactor { private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}") + private val HIDL_SHARED_LIBRARY = Regex( + "(?:android\\.(?:hardware|frameworks|hidl|system)|vendor\\.[A-Za-z0-9_]+\\.hardware)" + + "(?:\\.[A-Za-z0-9_]+)+@[0-9]+\\.[0-9]+(?:-[A-Za-z0-9_]+)*\\.so" + ) + private val hidlMatcher = object : ThreadLocal() { + override fun initialValue(): java.util.regex.Matcher = HIDL_SHARED_LIBRARY.toPattern().matcher("") + } + + private fun isHidlLoaderDiagnostic(input: String, match: MatchResult): Boolean { + val matcher = hidlMatcher.get()!! + val isLibrary = try { matcher.reset(match.value).matches() } finally { matcher.reset("") } + if (!isLibrary) return false + val start = match.range.first + val end = match.range.last + 1 + val prefix = "library \"" + val suffix = "\" not found" + val earliestQuote = (start - 4096).coerceAtLeast(0) + var quote = start - 1 + while (quote >= earliestQuote && input[quote] != '"') { + val char = input[quote] + if (!char.isLetterOrDigit() && char !in "/._-") return false + quote-- + } + if (quote < earliestQuote) return false + val pathStart = quote + 1 + if (pathStart < start && (input[start - 1] != '/' || + !(input.regionMatches(pathStart, "/vendor/", 0, 8) || + input.regionMatches(pathStart, "/system/", 0, 8)))) return false + val prefixStart = quote - prefix.length + 1 + val suffixEnd = end + suffix.length + return prefixStart >= 0 && suffixEnd <= input.length && + input.regionMatches(prefixStart, prefix, 0, prefix.length, ignoreCase = true) && + input.regionMatches(end, suffix, 0, suffix.length, ignoreCase = true) && + (prefixStart == 0 || !(input[prefixStart - 1].isLetterOrDigit() || input[prefixStart - 1] == '_')) && + (suffixEnd == input.length || !(input[suffixEnd].isLetterOrDigit() || input[suffixEnd] == '_')) + } + private val JWT_LABELLED = Regex("(?i)(\\bJWT[\\s=:]+)(\\d{8,})") private val JWT_BASE64 = Regex("ey[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}") private val GUID = Regex("\\b[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\\b") private val SECRET_KV = Regex( - "(?i)\\b(access[_-]?token|refresh[_-]?token|auth[_-]?token|authtoken|token|authcode|" + + "(?i)(\\b(?:access[_-]?token|refresh[_-]?token|auth[_-]?token|authtoken|token|authcode|" + "auth[_-]?ticket|ticket|sessionid|steamloginsecure|webapikey|api[_-]?key|" + - "machine[_-]?auth(?:[_-]?token)?|machineauth|password|passwd|pwd|secret)" + - "(\\s*[=:]\\s*|=)([^\\s\"'<>&;,]{4,})" + "machine[_-]?auth(?:[_-]?token)?|machineauth|password|passwd|pwd|secret)[\"']?\\s*[=:]\\s*)" + + "(?:([\"'])((?:\\\\.|(?!\\2)[^\\\\\\r\\n]){4,})\\2|([^\\s\"'<>&;,]{4,}))" ) private val GUARD_CODE = Regex( "(?i)((?:steam\\s*)?guard\\s*code[\\s:=]*|two[\\s-]?factor[\\s:=]*|2fa[\\s:=]*)([A-Za-z0-9]{5})" @@ -291,7 +328,7 @@ object LogRedactor { if (out.has("jwt")) out.set(JWT_LABELLED.replace(out.text) { "${it.groupValues[1]}" }) if ("ey" in out.text) out.set(JWT_BASE64.replace(out.text, "")) if (out.has("token", "auth", "ticket", "sessionid", "steamloginsecure", "api", "machine", "pass", "pwd", "secret")) { - out.set(SECRET_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}" }) + out.set(SECRET_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${it.groupValues[2]}" }) } if (out.has("guard", "factor", "2fa")) out.set(GUARD_CODE.replace(out.text) { "${it.groupValues[1]}" }) if (out.hasRun(32, ::isHex)) out.set(WEBAPI_KEY.replace(out.text, "")) @@ -309,7 +346,9 @@ object LogRedactor { } if (out.has("login")) out.set(LOGIN_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" }) for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "")) - if ('@' in out.text) out.set(EMAIL.replace(out.text, "")) + if ('@' in out.text) out.set(EMAIL.replace(out.text) { m -> + m.value.takeIf { isHidlLoaderDiagnostic(out.text, m) } ?: "" + }) if (out.has("jwt", "token", "ticket", "sessionid", "steamloginsecure", "machineauth")) { out.set(RESIDUAL.replace(out.text) { "${it.groupValues[1]}=" }) } 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/input/PadBridge.java b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java index a626d86002..cfb0978cb8 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java +++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java @@ -117,6 +117,16 @@ public final class PadBridge { if (changed && !on) resetBuiltin(); } + private static volatile int firstSlot; + + public static void setFirstSlot(int slot) { + firstSlot = slot; + } + + private int firstPlayerSlot() { + return firstSlot; + } + private void resetBuiltin() { routedTouch.clear(); systemGuidePressed = false; @@ -252,7 +262,9 @@ public final class PadBridge { public synchronized void syncConnectedControllers() { for (int deviceId : InputDevice.getDeviceIds()) { InputDevice device = InputDevice.getDevice(deviceId); - if (isFromController(device) && !excluded.test(deviceId)) publish(slotFor(device)); + if (!isFromController(device) || excluded.test(deviceId)) continue; + int slot = slotFor(device); + if (slot >= 0) publish(slot); } } @@ -272,6 +284,7 @@ public final class PadBridge { public synchronized boolean onKeyEvent(KeyEvent event) { if (!isControllerKeyEvent(event) || excluded.test(event.getDeviceId())) return false; int slot = slotFor(event.getDevice()); + if (slot < 0) return false; int side = JoyCon.side(event.getDevice()); if (side >= 0 && partners[slot] != NO_CONTROLLER && JoyCon.isRail(side, event.getScanCode())) return true; PadState pad = stateFor(slot); @@ -320,6 +333,7 @@ public final class PadBridge { if (!isControllerMotionEvent(event) || excluded.test(event.getDeviceId())) return false; if (event.getAction() != MotionEvent.ACTION_MOVE) return false; int slot = slotFor(event.getDevice()); + if (slot < 0) return false; PadState pad = stateFor(slot); noteDevice(event.getDevice(), slot); statAxes++; @@ -534,25 +548,25 @@ public final class PadBridge { if (owners[slot] != NO_CONTROLLER && InputDevice.getDevice(owners[slot]) == null) leave(slot, owners[slot]); } int side = JoyCon.side(device); - for (int slot = 0; side >= 0 && slot < SLOTS; slot++) { + for (int slot = firstPlayerSlot(); side >= 0 && slot < SLOTS; slot++) { if (owners[slot] == NO_CONTROLLER || partners[slot] != NO_CONTROLLER) continue; InputDevice owner = InputDevice.getDevice(owners[slot]); if (JoyCon.side(owner) != 1 - side) continue; partners[slot] = id; slotJoyCons.set(slot * 2 + side, id); slotJoyCons.set(slot * 2 + 1 - side, owner.getId()); - if (slot == 0) releaseBackPaddles(); + if (slot == firstPlayerSlot()) releaseBackPaddles(); stateFor(slot).clear(); Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") joins \"" + owner.getName() + "\" as player " + (slot + 1)); return slot; } - for (int slot = 0; slot < SLOTS; slot++) { + for (int slot = firstPlayerSlot(); slot < SLOTS; slot++) { if (owners[slot] != NO_CONTROLLER) continue; owners[slot] = id; Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") is player " + (slot + 1)); return slot; } - return 0; + return -1; } private PadState stateFor(int slot) { @@ -561,7 +575,8 @@ public final class PadBridge { private boolean isPrimary(KeyEvent event) { int id = event.getDevice().getId(); - return owners[0] == id || partners[0] == id; + int first = firstPlayerSlot(); + return owners[first] == id || partners[first] == id; } private void releaseBackPaddles() { @@ -580,7 +595,7 @@ public final class PadBridge { clearJoyCons(slot); if (slotControllers.get(slot) == id) slotControllers.set(slot, owners[slot]); if (activeControllerId == id) activeControllerId = owners[slot]; - if (slot == 0) releaseBackPaddles(); + if (slot == firstPlayerSlot()) releaseBackPaddles(); stateFor(slot).clear(); publish(slot); } @@ -596,8 +611,8 @@ public final class PadBridge { partners[slot] = NO_CONTROLLER; clearJoyCons(slot); slotControllers.set(slot, NO_CONTROLLER); + if (slot == firstPlayerSlot()) releaseBackPaddles(); if (slot == 0) { - releaseBackPaddles(); state.clear(); publish(); return; diff --git a/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt b/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt index ee84cffe46..e77b322f2b 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt @@ -13,6 +13,7 @@ import android.content.Context import android.os.Handler import android.os.HandlerThread import android.util.Log +import com.droiddeck.launcher.session.SessionState import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.ArrayDeque @@ -51,6 +52,10 @@ class SteamControllerBle(private val context: Context) { private fun connect() { if (!running || gatt != null) return + if (SessionState.suspended) { + handler.postDelayed(::connect, RETRY_MS) + return + } val adapter = (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter val bonded = runCatching { adapter?.takeIf(BluetoothAdapter::isEnabled)?.bondedDevices } .onFailure { Log.w(TAG, "paired devices unreadable", it) } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt index 73e6a75e9c..20714b552c 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt @@ -118,7 +118,8 @@ object DesktopCatalog { fun desktopPresent(context: Context): Boolean { val root = LinuxRuntime.rootDir(context) - return File(root, DesktopRemoval.PENDING).exists() || marker(context, DESKTOP_ID).exists() + return File(root, DesktopRemoval.PENDING).exists() || marker(context, DESKTOP_ID).exists() || + journal(root, DESKTOP_ID).exists() } fun desktopSize(context: Context): Long = DesktopRemoval.installedSize(context) @@ -126,8 +127,21 @@ object DesktopCatalog { fun cleanLegacy(context: Context, listener: LinuxRuntimeInstaller.ProgressListener? = null) = DesktopRemoval.cleanLegacy(context, listener) - fun removeDesktop(context: Context, listener: LinuxRuntimeInstaller.ProgressListener): String? = + fun removeDesktop(context: Context, listener: LinuxRuntimeInstaller.ProgressListener): String? = synchronized(installLock) { DesktopRemoval.remove(context, listener) + } + + internal fun discardDesktopInstall(context: Context) { + val entry = interrupted(context).firstOrNull { it.id == DESKTOP_ID } + val journal = journal(LinuxRuntime.rootDir(context), DESKTOP_ID) + entry?.let { + val download = downloadFile(context, it) + for (file in listOf(download, File(download.path + ".resume.properties"))) { + check(!file.exists() || file.delete()) { "Could not remove desktop download ${file.name}" } + } + } + check(!journal.exists() || journal.delete()) { "Could not clear desktop installation" } + } fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) { installLocked(context, entry, listener) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopRemoval.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopRemoval.kt index 3d031a85a7..ff244e6ad2 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopRemoval.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopRemoval.kt @@ -44,9 +44,10 @@ internal object DesktopRemoval { val root = LinuxRuntime.rootDir(context) val pending = File(root, PENDING) val marker = File(root, ".droiddeck-pkg-${DesktopCatalog.DESKTOP_ID}") - val version = FileUtils.readString(pending)?.trim() ?: FileUtils.readString(marker)?.trim() + val installing = DesktopCatalog.interrupted(root).firstOrNull { it.id == DesktopCatalog.DESKTOP_ID } + val version = FileUtils.readString(pending)?.trim() ?: installing?.version ?: FileUtils.readString(marker)?.trim() val versions = context.assets.open("desktop-removal/versions.txt").bufferedReader().use { it.readLines() } - check(version in versions) { context.getString(R.string.desktop_removal_unknown) } + check(version in versions && (installing == null || installing.version in versions)) { context.getString(R.string.desktop_removal_unknown) } val entries = lines(context, "kde-remove.tsv.gzip").map(DesktopFileRemoval.Entry::parse) val keep = protected(context, root) cleanLegacy(context, listener) @@ -63,6 +64,7 @@ internal object DesktopRemoval { if (!target.delete()) error("Could not remove $path") } } + DesktopCatalog.discardDesktopInstall(context) if (!pending.delete()) error("Could not finish desktop removal") Log.i("DesktopRemoval", "KDE: $result") listener.onProgress(context.getString(R.string.desktop_removed), 100) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/UserApps.kt b/app/src/main/java/com/droiddeck/launcher/runtime/UserApps.kt index 3bd000d7d1..b7ca15a18d 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/UserApps.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/UserApps.kt @@ -13,6 +13,7 @@ import com.caverock.androidsvg.SVG import com.droiddeck.launcher.R import com.droiddeck.launcher.core.Downloader import com.droiddeck.launcher.core.FileUtils +import com.droiddeck.launcher.core.Hashes import com.droiddeck.launcher.store.FlathubApi import org.json.JSONArray import org.json.JSONObject @@ -44,7 +45,7 @@ object UserApps { val fex: String = LinuxFex.AUTO, val arch: String? = null, ) - class Release(val tag: String, val published: String, val asset: String, val url: String) + class Release(val tag: String, val published: String, val asset: String, val url: String, val sha256: String? = null) sealed class UpdateCheck { class Current(val tag: String) : UpdateCheck() @@ -318,9 +319,12 @@ object UserApps { val r = releases.getJSONObject(i) if (r.optBoolean("draft")) return@mapNotNull null val assets = r.optJSONArray("assets") ?: return@mapNotNull null - val byName = (0 until assets.length()).associate { j -> assets.getJSONObject(j).let { it.getString("name") to it.getString("browser_download_url") } } + val byName = (0 until assets.length()).associate { j -> assets.getJSONObject(j).let { it.getString("name") to it } } pickAsset(byName.keys.toList())?.let { asset -> - r.optBoolean("prerelease") to Release(r.optString("tag_name", asset), r.optString("published_at"), asset, byName.getValue(asset)) + r.optBoolean("prerelease") to byName.getValue(asset).let { a -> + Release(r.optString("tag_name", asset), r.optString("published_at"), asset, a.getString("browser_download_url"), + Hashes.githubSha256(a.optString("digest"))) + } } } val pick = (candidates.firstOrNull { !it.first } ?: candidates.firstOrNull())?.second @@ -331,7 +335,7 @@ object UserApps { val download = File(context.cacheDir, "github-${release.asset}") try { val label = context.getString(R.string.user_apps_downloading, release.asset) - val ok = Downloader.downloadFile(release.url, download, false) { f -> onProgress(label, if (f < 0) -1 else Math.round(f * 100f)) } + val ok = Downloader.downloadFile(release.url, download, false, release.sha256) { f -> onProgress(label, if (f < 0) -1 else Math.round(f * 100f)) } return if (ok) use(download) else context.getString(R.string.user_apps_download_failed) } finally { download.delete() 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 c988bc5abf..d9d2d8e1d3 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -758,6 +758,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)) @@ -978,6 +988,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 e25bbc8218..5cb8fede7f 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 @@ -117,12 +124,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() + } } } @@ -134,6 +151,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 @@ -204,6 +229,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 @@ -217,8 +243,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 @@ -281,6 +315,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 @@ -727,7 +762,9 @@ class SessionService : Service() { private fun addControllerEnvironment(guest: MutableList, fakeInputDir: File, sessionDir: File) { FakeInputWriter.prepareRingSlots(fakeInputDir, 4) val builtinPad = SessionPrefs.builtinPad(this) - val hiddenPad = SessionState.mode == MODE_STEAM && !builtinPad + val hiddenPad = SessionState.mode == MODE_STEAM && !builtinPad && + !com.droiddeck.launcher.input.PadBridge.anyControllerConnected() + com.droiddeck.launcher.input.PadBridge.setFirstSlot(if (hiddenPad) 1 else 0) fakeInputDir.listFiles()?.forEach { file -> val node = Regex("event(\\d+)").matchEntire(file.name)?.groupValues?.get(1)?.toIntOrNull() if (file.name.startsWith(".uinput-") || (node != null && node >= FIRST_VIRTUAL_PAD) || @@ -1869,7 +1906,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" @@ -1914,8 +1953,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) @@ -1936,15 +1977,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 8fdbf5d244..0c430c1c5e 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/session/WinComponents.kt b/app/src/main/java/com/droiddeck/launcher/session/WinComponents.kt index c79171df26..2c5a1aa0d1 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/WinComponents.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/WinComponents.kt @@ -369,7 +369,9 @@ object WinComponents { val archiveName = archive.optString("name") val url = c.snapshot.substringBeforeLast('/') + "/" + archiveName val file = File(work, "${c.name}.files.tar.xz") - if (!Downloader.downloadFile(url, file, false) { f -> onProgress(Progress(c.name, archiveName, Phase.DOWNLOAD, if (f < 0) -1 else Math.round(f * 100f))) }) { + // The snapshot came straight from github.com, so its digest may vouch for a mirror's copy of the archive. + val sha = archive.optString("sha256").takeIf { it.matches(Regex("(?i)[0-9a-f]{64}")) } + if (!Downloader.downloadFile(url, file, false, sha) { f -> onProgress(Progress(c.name, archiveName, Phase.DOWNLOAD, if (f < 0) -1 else Math.round(f * 100f))) }) { return null to "download failed: $archiveName" } archive.optString("sha256").takeIf { it.length == 64 }?.let { sha -> 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 ccd7fd05e3..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 @@ -315,7 +317,7 @@ internal fun AppDialog( Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize().imePadding() - .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = close), + .tapOutside(close), ) { AnimatedVisibility( visibleState = shown, @@ -340,7 +342,7 @@ internal fun AppDialog( .clip(Shape16) .background(pal.surfaceVariant.copy(alpha = 0.97f)) .border(1.dp, pal.signal.copy(alpha = 0.22f), Shape16) - .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {} + .blockTouches() .controllerBack(back ?: close) .then(modifier) .then(if (scrollable) Modifier.verticalScroll(rememberScrollState()) else Modifier) @@ -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/DeckControlsPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/DeckControlsPanel.kt index c34d1a9710..0a603d5a54 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DeckControlsPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DeckControlsPanel.kt @@ -23,7 +23,9 @@ import android.widget.TextView import com.droiddeck.launcher.input.DeckControls import com.droiddeck.launcher.input.PadBridge import com.droiddeck.launcher.input.PadState +import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.session.SessionState import kotlin.math.atan2 import kotlin.math.hypot import kotlin.math.min @@ -85,9 +87,11 @@ class DeckControlsPanel( addView(tabs, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, dp(44))) } addView(centre, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f)) - addView(roundButton("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu, wide = true)) - addView(space(dp(8))) - addView(roundButton("•••", context.getString(R.string.drawer_open_qam), onQam, wide = true)) + if (SessionState.mode == SessionService.MODE_STEAM) { + addView(roundButton("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu, wide = true)) + addView(space(dp(8))) + addView(roundButton("•••", context.getString(R.string.drawer_open_qam), onQam, wide = true)) + } } private fun select(tab: Tab) { @@ -177,8 +181,10 @@ class DeckControlsPanel( place(pill("RB") { st, d -> st.press(PadState.RB, d) }, GamepadGeometry.Slot.RIGHT_INNER_SHOULDER) place(pill("RT") { st, d -> st.rightTrigger = if (d) 1f else 0f }, GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER) place(pill("VIEW") { st, d -> st.press(PadState.SELECT, d) }, GamepadGeometry.Slot.VIEW) - place(centreTap("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu), GamepadGeometry.Slot.STEAM) - place(centreTap("\u2022\u2022\u2022", context.getString(R.string.drawer_open_qam), onQam), GamepadGeometry.Slot.QAM) + if (SessionState.mode == SessionService.MODE_STEAM) { + place(centreTap("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu), GamepadGeometry.Slot.STEAM) + place(centreTap("\u2022\u2022\u2022", context.getString(R.string.drawer_open_qam), onQam), GamepadGeometry.Slot.QAM) + } place(pill("MENU") { st, d -> st.press(PadState.START, d) }, GamepadGeometry.Slot.MENU) place(centreTap("\u25a6 " + context.getString(R.string.deck_panels), context.getString(R.string.deck_more_controls)) { select(Tab.BOTH) }, GamepadGeometry.Slot.PANELS) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt index e1068a53cb..f6ce824ea8 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt @@ -52,6 +52,7 @@ import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -142,8 +143,13 @@ internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie PrimaryButton(open, enabled = !s.busy, main = true, large = true, icon = Icons.Outlined.DesktopWindows, onClick = click) }, beside = { - HeroIconButton(Icons.Outlined.Storefront, stringResource(R.string.flathub_name), FlathubTeal, "desktop:flathub") { at -> openFrom(at, null, "store") } - HeroIconButton(Icons.Filled.Add, stringResource(R.string.user_apps_add), null, "desktop:add") { if (!s.busy) adding = true } + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + HeroIconButton(Icons.Outlined.Storefront, stringResource(R.string.flathub_name), FlathubTeal, "desktop:flathub") { at -> openFrom(at, null, "store") } + HeroIconButton(Icons.Filled.Add, stringResource(R.string.user_apps_add), null, "desktop:add") { if (!s.busy) adding = true } + } + if (s.desktopPresent) UninstallDesktop(enabled = !s.runtimeActionsBlocked, onUninstall = a.onRemoveDesktop) + } }, rows = { tab -> if (tab == SheetTab.FILES) DesktopFiles(s, a) @@ -366,6 +372,7 @@ private fun DesktopFiles(s: FrontEndState, a: FrontEndActions) { @Composable private fun UninstallDesktop(enabled: Boolean, onUninstall: () -> Unit) { + val canUninstall by rememberUpdatedState(enabled) val colors = MaterialTheme.colorScheme val label = stringResource(R.string.common_uninstall) val title = stringResource(R.string.desktop_uninstall_title) @@ -383,7 +390,7 @@ private fun UninstallDesktop(enabled: Boolean, onUninstall: () -> Unit) { Text(note, fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.stepItem(1).padding(start = 4.dp, bottom = 12.dp)) Row(horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), modifier = Modifier.fillMaxWidth().stepItem(2)) { StepChoice(keep, enabled = open, modifier = Modifier.focusRequester(first)) { Steps.fold() } - StepChoice(label, danger = true, enabled = open) { Steps.fold(); onUninstall() } + StepChoice(label, danger = true, enabled = open && canUninstall) { Steps.fold(); onUninstall() } } }) } 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 9b65cc8a91..b5bbaa2e91 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 -> @@ -790,3 +791,21 @@ private fun LanguageRow(host: MenuHost, chosen: String, onPick: (String) -> Unit } } } + +/** The two colours of the Gradient theme, each a small square that opens the colour picker. */ +@Composable +private fun GradientColorRows() { + val ctx = androidx.compose.ui.platform.LocalContext.current.applicationContext + val (primary, secondary) = Themes.gradientColors + var picking by remember { androidx.compose.runtime.mutableIntStateOf(0) } + val primaryLabel = stringResource(R.string.theme_gradient_primary) + val secondaryLabel = stringResource(R.string.theme_gradient_secondary) + SettingsRow(primaryLabel, null) { ColorCube(androidx.compose.ui.graphics.Color(primary), primaryLabel) { picking = 1 } } + SettingsRow(secondaryLabel, null) { ColorCube(androidx.compose.ui.graphics.Color(secondary), secondaryLabel) { picking = 2 } } + if (picking != 0) ColorPickerDialog( + if (picking == 1) primaryLabel else secondaryLabel, if (picking == 1) primary else secondary, + onDismiss = { picking = 0 }, + ) { argb -> + if (picking == 1) Themes.setGradient(ctx, argb, secondary) else Themes.setGradient(ctx, primary, argb) + } +} 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 49564945f0..a444f37115 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -86,6 +86,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, @@ -137,6 +138,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 = {}, @@ -287,6 +289,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/SecondScreenPresentation.kt b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt index df972e00f4..04809ea5c2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt @@ -157,16 +157,18 @@ class SecondScreenPresentation( } } controls.addView(keyboardButton) - controls.addView(Button(context).apply { - text = "STEAM" - contentDescription = context.getString(R.string.deck_open_steam_menu) - setOnClickListener { onSteamMenu() } - }) - controls.addView(Button(context).apply { - text = "…" - contentDescription = context.getString(R.string.drawer_open_qam) - setOnClickListener { onQam() } - }) + if (SessionState.mode == SessionService.MODE_STEAM) { + controls.addView(Button(context).apply { + text = "STEAM" + contentDescription = context.getString(R.string.deck_open_steam_menu) + setOnClickListener { onSteamMenu() } + }) + controls.addView(Button(context).apply { + text = "…" + contentDescription = context.getString(R.string.drawer_open_qam) + setOnClickListener { onQam() } + }) + } panel.addView(controls, FrameLayout.LayoutParams(-1, -2, Gravity.TOP)) root.addView(panel, weightParams()) val host = KeyboardHost(context) { sessionActivity.dispatchKeyEvent(it) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt index 38bbb76cf9..4a0adea2d4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt @@ -221,7 +221,7 @@ fun LoadingOverlay( modifier = Modifier .fillMaxSize() .background(colors.background) - .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}, + .blockTouches(), ) { CapsuleWall(games, driftMs = 65_000, modifier = Modifier.alpha(0.3f)) Box( @@ -350,7 +350,6 @@ private fun CancelHint(onCancel: () -> Unit, modifier: Modifier = Modifier) { fun SessionPausedOverlay(title: String = stringResource(R.string.load_steam_paused), onResume: () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current - val interactionSource = remember { MutableInteractionSource() } val resumeFocus = remember { FocusRequester() } LaunchedEffect(Unit) { androidx.compose.runtime.withFrameNanos { } @@ -360,7 +359,7 @@ fun SessionPausedOverlay(title: String = stringResource(R.string.load_steam_paus modifier = Modifier .fillMaxSize() .background(pal.background.copy(alpha = 0.94f)) - .clickable(interactionSource = interactionSource, indication = null) {}, + .blockTouches(), contentAlignment = Alignment.Center, ) { Column( 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 d32e1e3ea4..58b4c11eea 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -103,6 +103,7 @@ import androidx.compose.animation.slideOutHorizontally import androidx.compose.foundation.LocalIndication import androidx.compose.foundation.border import androidx.compose.foundation.focusable +import androidx.compose.ui.focus.focusProperties import androidx.compose.foundation.hoverable import androidx.compose.foundation.interaction.collectIsFocusedAsState import androidx.compose.foundation.interaction.collectIsHoveredAsState @@ -277,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, @@ -312,7 +315,7 @@ class DrawerActions( @OptIn(ExperimentalComposeUiApi::class) @Composable internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, controllerActive: Boolean, onPageChange: (SessionDrawerPage) -> Unit, a: DrawerActions) { - val pages = sessionDrawerPages(a.steam && a.secondScreenDisplays.isNotEmpty(), a.glassesPresent) + val pages = sessionDrawerPages(a.secondScreenDisplays.isNotEmpty(), a.glassesPresent) val page = requestedPage.takeIf { it in pages } ?: SessionDrawerPage.CONTROLLER LaunchedEffect(requestedPage, pages) { if (page != requestedPage) onPageChange(page) } val colors = MaterialTheme.colorScheme @@ -384,10 +387,15 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont focus.request(first) } } - if (open || veil > 0.01f) Box( - modifier = Modifier.fillMaxSize() - .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { host.open = null; a.onClose() }, - ) + if (open || veil > 0.01f) { + val closeLabel = stringResource(R.string.common_close) + Box( + modifier = Modifier.fillMaxSize() + .focusProperties { canFocus = false } + .semantics { contentDescription = closeLabel } + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClickLabel = closeLabel) { host.open = null; a.onClose() }, + ) + } androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) { val short = maxHeight < 440.dp val sheetWidth = minOf(360.dp, maxWidth * 0.92f) @@ -401,7 +409,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont modifier = Modifier .fillMaxSize() .background(pal.background.copy(alpha = 0.97f)) - .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {} + .blockTouches() .focusGroup() .controllerBack { if (host.open != null) host.open = null else a.onClose() @@ -569,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), @@ -748,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)) @@ -785,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), ) { @@ -811,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)) @@ -830,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 }, ) { @@ -851,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) @@ -884,7 +897,7 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List Unit): Modifier = onPreviewKe } } +internal fun Modifier.blockTouches(): Modifier = pointerInput(Unit) { detectTapGestures { } } + +internal fun Modifier.tapOutside(onTap: () -> Unit): Modifier = + pointerInput(onTap) { detectTapGestures(onTap = { onTap() }) } + internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modifier = onPreviewKeyEvent { event -> val keyEvent = event.nativeKeyEvent val previous = keyEvent.keyCode == KeyEvent.KEYCODE_BUTTON_L1 @@ -170,7 +179,7 @@ internal fun TabStrip( if (bumpers) BumperKey("LB", stringResource(R.string.widgets_prev_tab)) { onSelect((selected + tabs.size - 1) % tabs.size) } Row( modifier = Modifier.weight(1f, fill = false).clip(shape).background(colors.surfaceVariant).border(1.dp, pal.line2, shape) - .horizontalScroll(scroll).padding(3.dp), + .horizontalScroll(scroll).selectableGroup().padding(3.dp), ) { tabs.forEachIndexed { i, label -> val on = i == selected @@ -190,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), ) @@ -360,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), ) { @@ -393,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), ) { @@ -784,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 @@ -803,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 e0d5099a74..1492362f12 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt @@ -303,7 +303,7 @@ internal fun SessionAchievementsPanel(label: String, state: AchievementsState, t val slide = remember { MutableTransitionState(false).apply { targetState = true } } BoxWithConstraints( Modifier.fillMaxSize().background(veil) - .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onClose), + .tapOutside(onClose), contentAlignment = Alignment.CenterEnd, ) { val short = maxHeight < 440.dp @@ -312,7 +312,7 @@ internal fun SessionAchievementsPanel(label: String, state: AchievementsState, t (if (floating) Modifier.padding(12.dp).fillMaxHeight().width(minOf(420.dp, maxWidth * 0.92f)).clip(RoundedCornerShape(20.dp)) .background(pal.background).border(1.dp, pal.line2, RoundedCornerShape(20.dp)) else Modifier.fillMaxHeight().width(minOf(420.dp, maxWidth * 0.92f)).background(pal.background.copy(alpha = 0.97f))) - .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {} + .blockTouches() .controllerBack(onClose) .then(if (kinds.isEmpty()) Modifier else Modifier.bumpers({ pick = (pick + kinds.size - 1) % kinds.size }, { pick = (pick + 1) % kinds.size })) .padding(if (short) 12.dp else 16.dp), @@ -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 c8944df418..7001fa9167 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1457,6 +1457,14 @@ خلفية سوداء ونص أبيض، والأزرق لكل عنصر محدَّد أو مُركَّز عليه أو مضغوط. كحلي كهربائي أزرق أكثر سطوعًا، على أسطح تميل إلى الكحلي بدلاً من الرمادي. + تدرج لوني + لونك الأساسي والثانوي، ممزوجان على الأزرار وعناصر التمييز. + الأساسي + الثانوي + درجة اللون + التشبع + السطوع + لون سداسي (Hex) Esc Ins Del @@ -2596,6 +2604,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 502f0234fd..16db21a9b9 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1026,6 +1026,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 @@ -1465,6 +1466,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 6a2f7582a3..9dcc424a11 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -1401,6 +1401,14 @@ Черен фон, бял текст, синьото за всичко избрано, на фокус или натиснато. Яркосиньо По-яркото синьо, върху повърхности, по-близки до тъмносиньо, вместо сиво. + Градиент + Вашите основен и вторичен цвят, смесени в бутоните и акцентите. + Основен + Вторичен + Нюанс + Наситеност + Яркост + Hex цвят Esc Ins Del @@ -2496,6 +2504,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 4043043803..97e6799605 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1429,6 +1429,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 @@ -2546,6 +2554,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 e043f3ac25..0c2bc230b3 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -1401,6 +1401,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 @@ -2496,6 +2504,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 6615713b14..c09e49dd7e 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 84f49be0c2..181822f35e 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1401,6 +1401,14 @@ Μαύρο φόντο, λευκά γράμματα, το μπλε για ό,τι είναι επιλεγμένο, εστιασμένο ή πατημένο. Ηλεκτρικό ναυτικό μπλε Το μπλε πιο έντονο, σε επιφάνειες που τείνουν προς το ναυτικό μπλε αντί για γκρι. + Διαβάθμιση + Δικά σας πρωτεύον και δευτερεύον χρώμα, σε μίξη στα κουμπιά και τις επισημάνσεις. + Πρωτεύον + Δευτερεύον + Απόχρωση + Κορεσμός + Φωτεινότητα + Χρώμα hex Esc Ins Del @@ -2496,6 +2504,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 92a8957205..ec99ab7198 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 84b55022f5..ac12cc7e89 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -1401,6 +1401,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 @@ -2496,6 +2504,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 c89604d268..143d11449b 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 2dff496b2c..1135072324 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -1401,6 +1401,14 @@ काली ज़मीन, सफ़ेद टाइप, चुने, फ़ोकस या दबाए गए हर चीज़ के लिए ब्लू रंग। इलेक्ट्रिक नेवी ब्लू रंग ज़्यादा चमकीला, उन सतहों पर जो ग्रे के बजाय नेवी की ओर झुकती हैं। + ग्रेडिएंट + आपके अपने प्राथमिक और द्वितीयक रंग, बटनों और हाइलाइट पर मिश्रित। + प्राथमिक + द्वितीयक + रंगत + संतृप्ति + चमक + हेक्स रंग Esc Ins Del @@ -2496,6 +2504,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 e3edb7ef41..a1638350ab 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -1401,6 +1401,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 @@ -2496,6 +2504,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 8d3e41a1d8..61bb207a00 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -1387,6 +1387,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 @@ -2471,6 +2479,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 de3de5b336..0d8fd58828 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 d18f60b926..7b719791fd 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -1389,6 +1389,14 @@ 黒の背景に白の文字、選択・フォーカス・押下時には青を使用します。 エレクトリックネイビー より明るい青を、グレーではなくネイビー寄りの画面に使用します。 + グラデーション + 自分で選んだプライマリとセカンダリの色を、ボタンやハイライトにグラデーションで使います。 + プライマリ + セカンダリ + 色相 + 彩度 + 明度 + 16進カラー Esc Ins Del @@ -2473,6 +2481,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 6472128020..0ea3c7b1be 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -1389,6 +1389,14 @@ 검은색 배경에 흰색 글자, 선택·포커스·누름 상태에는 파란색을 사용합니다. 일렉트릭 네이비 회색 대신 네이비 톤의 화면에 더 밝은 파란색을 사용합니다. + 그라데이션 + 직접 고른 기본색과 보조색이 버튼과 강조 표시에 섞여 적용됩니다. + 기본색 + 보조색 + 색조 + 채도 + 명도 + 16진수 색상 Esc Ins Del @@ -2473,6 +2481,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 c9962a55fb..2e3eb1205d 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -1387,6 +1387,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 @@ -2471,6 +2479,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 c870a048ee..e0ee85176d 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -1401,6 +1401,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 @@ -2496,6 +2504,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 dc3e6c42c1..93b6ab06fc 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1401,6 +1401,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 @@ -2496,6 +2504,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 666a47b293..288e644bae 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1429,6 +1429,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 @@ -2549,6 +2557,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 1ef3830ae6..91e75d38fc 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 9ef9a8606b..45bd06550c 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 a70b63efc9..4b434247a5 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -1415,6 +1415,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 @@ -2521,6 +2529,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 bab62122fc..592685d837 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 8b9be87c23..5f75e21777 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -1401,6 +1401,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 @@ -2496,6 +2504,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 648aff3f40..d2c04317c6 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -1387,6 +1387,14 @@ พื้นดำ ตัวอักษรขาว สีฟ้าสำหรับทุกสิ่งที่ถูกเลือก โฟกัส หรือกด กรมท่าไฟฟ้า สีฟ้าสว่างขึ้น บนพื้นผิวที่เอียงไปทางกรมท่ามากกว่าเทา + ไล่เฉดสี + สีหลักและสีรองที่คุณเลือกเอง ผสมกันบนปุ่มและส่วนที่เน้น + สีหลัก + สีรอง + เฉดสี + ความอิ่มตัว + ความสว่าง + สีเลขฐานสิบหก Esc Ins Del @@ -2471,6 +2479,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 58cebb95e6..24fc12e92d 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -605,7 +605,7 @@ Sahte HDR VR SteamVR - SteamVR\'ı başlat + SteamVR\'ye gir SteamVR denetleniyor… Bant giderme Bant giderme gücü @@ -626,9 +626,9 @@ Klavye Gecikme Düşük gecikmeli kumanda - Kumanda 250 Hz yerine 1000 Hz bildirir. Biraz daha fazla CPU. + Kumanda 250 Hz yerine 1000 Hz bildirir. CPU kullanımı biraz artar. Düşük gecikmeli dokunma - Dokunuşlar kare birleştirmeyi atlar; Steam dokunmatik kontrolleri 1000 Hz çalışır. Biraz daha fazla CPU. + Dokunmalar kare gruplamasını atlar; Steam dokunmatik kontrolleri 1000 Hz çalışır. CPU kullanımı biraz artar. PC klavyesi Android İkinci ekran @@ -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. @@ -1285,15 +1287,15 @@ %1$s %2$s sürümüne güncellendi. %1$s %2$s sürümüne güncellendi. Ekran sürücüsü, DroidDeck yeniden başlatıldıktan sonra uygulanır. Sürücü güncellemeleri oturum bitene kadar bekler. - %1$s %2$s, mobil veriyi ve pil tasarrufunu kapattığınızda indirilecek. - %1$s %2$s burada oturum başlatmadı, bu yüzden Otomatik çalışan sürücülerde kalıyor. - %1$s iki kez oturum başlatmadı, bu yüzden Otomatik çalışan sürücülere geri döndü. + %1$s %2$s, mobil veriden ve pil tasarrufundan çıkınca indirilecek. + %1$s %2$s burada oturum başlatamadı, bu yüzden Otomatik, oturum başlatabilen sürücülerde kalıyor. + %1$s iki kez oturum başlatamadı, bu yüzden Otomatik, sorunsuz çalışan önceki sürücülere döndü. %1$s %2$s sürümüne geçildi. %1$s %2$s sürümüne geçildi. Ekran sürücüsü, DroidDeck yeniden başlatıldıktan sonra uygulanır. Kullanılan: %1$s %2$s. Kullanılan: %1$s %2$s. Ekran sürücüsü, DroidDeck yeniden başlatıldıktan sonra uygulanır. - Pakette gelen Quest görüntü sürücüsü ve varsayılan çalışma zamanı kullanılıyor. - Pakette gelen Quest görüntü sürücüsü ve varsayılan çalışma zamanı kullanılıyor. Görüntü sürücüsü DroidDeck yeniden başladıktan sonra geçerli olur. + Pakete dahil Quest ekran sürücüsü ve çalışma zamanı varsayılanı kullanılıyor. + Pakete dahil Quest ekran sürücüsü ve çalışma zamanı varsayılanı kullanılıyor. Ekran sürücüsü DroidDeck yeniden başladıktan sonra uygulanır. Sürücü zip dosyası değil: ne AdrenoTools sürücüsü, ne -Linux Turnip ne de Android + Linux paketi İçe aktarma başarısız oldu: %1$s İçe aktarılan sürücü @@ -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 @@ -1715,7 +1725,7 @@ DroidDeck\'e geri dönmek için dokunun. Kablosuz hata ayıklamayı şimdi kapatabilirsiniz. Kablosuz hata ayıklama kurulumu durdu - İndirme başarısız oldu + İndirme başarısız İndirme boyutu yayınlanan APK ile eşleşmedi ve atıldı - yeniden deneyin İndirme, sağlama toplamıyla eşleşmedi ve atıldı - yeniden deneyin Güncelleme, %2$s değil %1$s Android paketi içindir @@ -1814,7 +1824,7 @@ GitHub\'ın hız sınırına ulaşıldı - daha sonra yeniden deneyin GitHub HTTP %1$d yanıtı verdi - İndirme başarısız oldu + İndirme başarısız Bu sürücü listesi sağlama toplamlarından önceki bir tarihe ait - yenileyip yeniden deneyin Sağlama toplamı uyuşmuyor - indirme atıldı Bir AdrenoTools sürücüsü değil: %1$s @@ -2177,14 +2187,14 @@ SteamGridDB\'de ara… SteamGridDB: %1$s Oyun ara - Diğer sonuçlar - Sonuç yok. - SteamGridDB bir API anahtarı gerektiriyor. Kendinizinkini Kurulum › Başlatıcı bölümüne ekleyin. - SteamGridDB API anahtarını kabul etmedi. Kurulum › Başlatıcı bölümünden denetleyin. - SteamGridDB şu anda istekleri sınırlıyor. Bir dakika sonra yeniden deneyin. - SteamGridDB\'ye ulaşılamadı. Bağlantınızı denetleyin. - SteamGridDB\'de bir sorun oluştu. Daha sonra yeniden deneyin. - SteamGridDB\'de bu oyun için sonuç yok. Aramayı deneyin. + Diğer eşleşmeler + Hiçbir şey bulunamadı. + SteamGridDB bir API anahtarı ister. Kurulum › Başlatıcı bölümüne kendi anahtarınızı ekleyin. + SteamGridDB API anahtarını kabul etmedi. Kurulum › Başlatıcı bölümünden kontrol edin. + SteamGridDB şu anda istekleri sınırlıyor. Bir dakika sonra tekrar deneyin. + SteamGridDB\'ye ulaşılamadı. Bağlantıyı kontrol edin. + SteamGridDB\'de bir sorun oluştu. Daha sonra tekrar deneyin. + SteamGridDB\'de bu oyun için eşleşme yok. Bir arama deneyin. %1$d oyun eklendi %1$d oyun eklendi @@ -2213,44 +2223,44 @@ Çalışma ortamı ve ekran sürücülerini ayrı ayrı %1$s kullanılsın mı? Sürücüler nasıl seçilir - Bu GPU için en iyi eşleşme, her zaman güncel + Bu GPU için en iyi çift, güncel tutulur Eşleşen çift Bir çift seçin; iki sürücüyü birden ayarlar - Serbest eşleştir - Görüntü ve çalışma zamanını ayrı ayrı seçin + Karıştır ve eşleştir + Ekran ve çalışma zamanını ayrı ayrı seçin Çift - Karışık - OTO + Karma + OTOMATİK ÇİFT PAKET - SEÇİLİ + SEÇİLEN GPU\'YA GÖRE VARSAYILAN - Şimdi çiziyor - Yeniden başlatma bekliyor · o zamana kadar %1$s çiziyor - Çalışıyor - Sonraki oturum · bu oturumda %1$s kalır - Ekranı çizer. Sonraki oturumdan itibaren geçerli. + Şu an çiziyor + Yeniden başlatma bekliyor · o zamana kadar %1$s çizer + Şu an çalışıyor + Sonraki oturum · bu oturum %1$s kullanmaya devam eder + Ekranı çizer. Sonraki oturumdan itibaren uygulanır. önceki sürücü - Görüntü sürücüsünü değiştirmek için yeniden başlatın. - Görüntü sürücüsünü değiştirmek için oturumu durdurup DroidDeck\'i yeniden başlatın. + Ekran sürücüsünü değiştirmek için yeniden başlatın. + Çalışan oturumu durdurun, sonra ekran sürücüsünü değiştirmek için DroidDeck\'i yeniden başlatın. Şimdi yeniden başlat Sonra - Otomatik, %1$s için bu çifti seçti - Otomatik, %1$s için yerleşik sürücüleri kullanıyor + Otomatik, %1$s cihazınız için bu çifti seçti + Otomatik, %1$s cihazınız için yerleşik sürücüleri kullanıyor %1$s ailesi için seçildi. Yeni sürümler arka planda kurulur. Bir çift seçin - Bir çift, görüntü sürücüsünü ve çalışma zamanı sürücüsünü birlikte ayarlar. + Bir çift, ekran ve çalışma zamanı sürücülerini birlikte ayarlar. Her sürücüyü seçin - Bir paket iki yuvayı da doldurur. Görüntü değişiklikleri yeniden başlatmadan sonra, çalışma zamanı değişiklikleri sonraki oturumdan itibaren geçerli olur. - Görüntü sürücüsünü değiştir + Bir paket iki yuvayı da doldurur. Ekran değişiklikleri yeniden başlatmadan sonra, çalışma zamanı değişiklikleri sonraki oturumda uygulanır. + Ekran sürücüsünü değiştir Çalışma zamanı sürücüsünü değiştir - OTOMATİK SEÇİMİ - Kurulu + OTOMATİK\'İN SEÇİMİ + Yüklü %1$s + %2$s %1$s · uygulamak için yeniden başlatın %1$s · yeniden başlatma bekliyor - Bu aygıt + Bu cihaz %1$s kaldırılsın mı? Tanılama Oynamaya hazır @@ -2262,11 +2272,11 @@ Görünüm Bu cihaz Kütüphane görselleri - İndirme + İndirmeler Kaynak Otomatik Doğrudan - Ayna + Yansı Özel önek Site Önek @@ -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. @@ -2531,7 +2542,7 @@ Yeterli boş alan yok: %1$s gerekli, yalnızca %2$s boş Yetersiz alan (%1$s boş, %2$s gerekli) Boş alan bilinmiyor - Resim konumu + Görüntü konumu Üst Alt Orta (varsayılan) @@ -2539,71 +2550,71 @@ Depolama ölçülüyor… İlk seferde birkaç saniye sürer. Dahili depolama - %2$s alanın %1$s kadarı kullanılıyor + %2$s içinde %1$s kullanıldı %1$s boş - DroidDeck %1$s yer kaplıyor. Ölçüm: %2$s. + DroidDeck %1$s kullanıyor. %2$s saatinde ölçüldü. yeniden ölçülüyor… Diğer Android uygulamaları - Şimdi boşaltılabilir - Kullanılmayan çalışma zamanları, kalıntılar, eski günlükler + Şimdi güvenle boşaltılabilir + Kullanılmayan çalışma zamanları, artıklar, eski günlükler Temizle… - Temizlemek veya kaldırmak için oturumu durdurun. Boyutlar görünmeye devam eder. + Bir şeyi temizlemek veya kaldırmak için oturumu durdurun. Boyutlar yine de gösterilir. Nereye gidiyor Steam oyunları Oyun verileri Önekler %1$s · atölye %2$s · gölgelendiriciler %3$s - Proton ve çalışma zamanları + Proton & çalışma zamanları %1$s kullanılmıyor - GOG, Epic ve diğer mağazalar - Mağazalar bölümünden kaldırın + GOG, Epic & diğer mağazalar + Bunları Mağazalar\'dan kaldırın Masaüstü uygulamaları Flatpak uygulamaları ve çalışma zamanları - Linux sistemi ve Steam istemcisi - Herhangi bir şeyin çalışması için gerekli + Linux sistemi & Steam istemcisi + Herhangi bir şeyi çalıştırmak için gerekli DroidDeck verileri - Eski oturum günlükleri %1$s · önbellek · sürücüler + Eski oturum günlükleri %1$s · önbellekler · sürücüler Oyunlar Oyun verileri - Proton ve çalışma zamanları + Proton & çalışma zamanları Diğer mağazalar Masaüstü uygulamaları Linux sistemi DroidDeck - Temizlik - Burada hiçbir şey kurulu oyunlara veya süren indirmelere dokunmaz. + Temizle + Burada hiçbir şey yüklü oyunlarınıza veya süren indirmelerinize dokunmaz. Şu anda temizlenecek bir şey yok. - Seçili: %1$s · %2$s → %3$s boş + Seçilen: %1$s · %2$s → %3$s boş Temizleniyor… %1$s boşalt %1$s boşaltıldı. - Kullanılmayan Steam çalışma zamanları ve Proton - Kaldırılmış oyunların kalıntıları - Kayıt içerebilecek kalıntılar + Kullanılmayan Steam çalışma zamanları ve Proton\'lar + Kaldırılan oyunlardan kalan artıklar + Kayıt tutabilecek artıklar Eski oturum günlükleri - Geçerli oturumun günlükleri tutulur - Hiçbir oyun kullanmıyor. Gerekirse Bileşenler bölümünden yeniden yükleyin. - Kurulu oyunların gölgelendirici önbelleği - Oynarken yeniden oluşur. Her oyunun ilk dakikaları yine takılır. + Geçerli oturumun günlükleri korunur + Hiçbir oyun buna ayarlı değil. Gerekirse Bileşenler\'den yeniden yükleyin. + Yüklü oyunların gölgelendirici önbellekleri + Oynadıkça yeniden oluşur. Her oyunun ilk dakikalarında yine takılma olur. Güvenli Kullanılmıyor Takılma - Kayıtları denetleyin + Kayıtları kontrol et Varsayılan Gerekli Kullanılmıyor Depolama - Verileriyle birlikte %1$s + %1$s, verileriyle birlikte En büyük En az oynanan SD kartta Burada oyun yok. - %1$s oynandı + Oynanma: %1$s Hiç oynanmadı Oyun %1$s · veri %2$s - Kaldır - Kaldırma, Steam\'in kaydetmesi için Steam penceresini açar. Bir oyunu SD karta taşımak için Steam › Ayarlar › Depolama yolunu kullanın. + Yüklemeyi kaldır + Yüklemeyi kaldırma, Steam\'in kendi iletişim kutusunu açar; böylece Steam kaydı tutar. Bir oyunu SD karta taşımak için Steam › Ayarlar › Depolama\'yı kullanın. %1$s kaldırılsın mı? - Steam açılır ve onay ister. Bu, oyunun %1$s alanını boşaltır. Kalıntıları temizleyene kadar önek kalır ve Steam Cloud kayıtları hesabınızda kalır. + Steam açılır ve onay ister. Bu, oyunun %1$s alanını boşaltır. Öneki, artıkları temizleyene kadar kalır ve Steam Cloud kayıtları hesabınızda durur. Steam\'i aç %1$s · %2$s kullanılmıyor Kullanılmayanları kaldır · %1$s @@ -2611,30 +2622,30 @@ Kullanılmıyor Kaldır %1$s kaldırılsın mı? - %1$s boşaltır. Bir oyun gerektirirse Steam yeniden indirir. + %1$s boşaltır. Bir oyun isterse Steam yeniden indirir. Linux x86 oyunları için gerekli (FEX) ARM64 Proton\'lar için gerekli - Oyunların istediği VC++ ve DirectX kurulumları + Oyunların istediği VC++ ve DirectX yükleyicileri Linux x86 oyunlarını çalıştırır Steam aracı DroidDeck oyunları bu çalışma zamanı olmadan çalıştırır - DroidDeck\'in çalıştıramadığı Proton x86 - Tüm oyunlar için varsayılan - Hiçbir oyun kullanmıyor - Steam ayarları okunamıyor, bu yüzden tutuluyor + x86 Proton, DroidDeck bunu çalıştıramaz + Her oyun için varsayılan + Hiçbir oyun buna ayarlı değil + Steam\'in ayarları okunamadı, bu yüzden korunuyor Depolama temizliğinin bitmesini bekleyin Yalnızca %1$s boş - Steam\'in güncellemeler ve gölgelendirici önbelleği için alana ihtiyacı var. 10 GB altında oyun güncellemeleri yarıda kalabilir. - %1$s risksiz boşaltılabilir. + Steam\'in güncellemeler ve gölgelendirici önbellekleri için yere ihtiyacı var. 10 GB\'ın altında oyun güncellemeleri yarıda başarısız olabilir. + %1$s güvenle boşaltılabilir. Yer aç Yine de oyna - %d kurulu - %d kurulu + %d yüklü + %d yüklü - %d SD kartta - %d SD kartta + SD kartta %d + SD kartta %d %d araç @@ -2645,15 +2656,15 @@ %d oyunun boş önek klasörleri ve gölgelendirici önbelleği - %d oyunun önekinde hâlâ dosyalar var; yerel kayıtlar da olabilir. Gerekirse önce bir kopya alın. - %d oyunun önekinde hâlâ dosyalar var; yerel kayıtlar da olabilir. Gerekirse önce bir kopya alın. + %d oyunun öneki hâlâ dosya içeriyor, bunlar yerel kayıtları da içerebilir. İsterseniz önce yedekleyin. + %d oyunun önekleri hâlâ dosya içeriyor, bunlar yerel kayıtları da içerebilir. İsterseniz önce yedekleyin. %d oyun %d oyun - DroidDeck varsayılan Proton - DroidDeck Proton 11 seçeneği + DroidDeck\'in varsayılan Proton\'u + DroidDeck\'in Proton 11 seçeneği %d oyun kullanıyor %d oyun kullanıyor @@ -2662,41 +2673,41 @@ Bileşenler Kullanılmayan bileşenler Orijinal %1$s · %2$s - %1$s boşaltır. Yalnızca artık kurulu olmayan bir Proton sürümünü geri yükler. - Denetlenmedi: bir Steam uygulamasının manifest dosyası okunamıyor, bu yüzden kaldırılmış oyunların önekleri okunana kadar kalır. + %1$s boşaltır. Yalnızca artık yüklü olmayan bir Proton sürümünü geri yükler. + Denetlenmedi: bir Steam uygulama manifesti okunamadı, bu yüzden kaldırılan oyunların önekleri manifest okunabilene kadar korunuyor. Tamamlanamadı: %1$s - Paylaşılan %1$s - Kurulu oyunlar + paylaşılan %1$s + Yüklü oyunlar Önek %1$s · gölgelendiriciler %2$s · atölye %3$s - Gölgelendiricileri sil - Kaldırılmış oyunlar + Gölgelendiricileri temizle + Kaldırılan oyunlar Steam uygulaması %1$d - Önekinde hâlâ dosyalar var; yerel kayıtlar da olabilir - Önekini (Wine) ve gölgelendirici önbelleğini siler (%1$s). Gerekli kayıtların önce bir kopyasını alın; Steam Cloud kayıtları hesabınızda kalır. - Tutulanlar - Steam dışı oyunlar ve ortak Steam öneki - Mağazaların veya elle eklenen oyunların önekleri + Öneki hâlâ dosya içeriyor, bunlar yerel kayıtları da içerebilir + Wine önekini ve gölgelendirici önbelleğini (%1$s) siler. Önce istediğiniz kayıtları yedekleyin; Steam Cloud kayıtları hesabınızda durur. + Korunan + Steam dışı oyunlar ve Steam\'in ortak öneki + Mağazalardan veya elle eklenen oyunların önekleri İndirilen paketler - Tutulan orijinaller + Kaydedilen orijinaller İndirilmiş bileşen paketi yok. Bir Proton veya oyun için seçili Hiçbir yerde seçili değil - Kurulu Proton\'ı geri yükler - Artık kurulu olmayan Proton sürümü + Yüklü Proton\'u geri yükler + Artık yüklü olmayan Proton sürümü Kullanımda - Kullanımdaki bileşenler kilitli kalır. Onları Bileşenler bölümünden seçin; burada kaldırdığınız paketler oradan yeniden indirilebilir. + Kullanımdaki bileşenler kilitli kalır. Bileşenler\'den seçin; burada kaldırılan her şey oradan yeniden indirilebilir. %1$s boşaltır. Kendi içe aktardığınız paketler yeniden indirilemez. - Flatpak uygulamaları için %1$s ve bunların paylaştıkları + Flatpak uygulamaları ve paylaştıkları şeyler için %1$s Uygulamalar Kurulu Flatpak uygulaması yok. - Uygulamaların paylaştıkları + Uygulamaların ortak kullandıkları Çalışma zamanları - Uygulamaların üzerinde çalıştığı kitaplıklar; kullanılmayanlar Kullanılmayanları kaldır ile gider + Uygulamaların üzerinde çalıştığı kütüphaneler; kullanılmayanlar Kullanılmayanları kaldır ile gider İndirme deposu - Flatpak object store ve önbelleğe alınmış indirmeler + Flatpak\'in nesne deposu ve önbelleğe alınmış indirmeler Kullanılmayanları kaldır - Kurulu hiçbir uygulamanın istemediği çalışma zamanlarını kaldırır ve Flatpak object store\'u temizler. Kurulu uygulamalar çalışmaya devam eder. - Uygulamayı (%1$s) ve başka kimsenin kullanmadığı çalışma zamanlarını kaldırır. Ev klasöründeki verileri kalır. + Kurulu hiçbir uygulamanın ihtiyaç duymadığı çalışma zamanlarını kaldırır ve Flatpak\'in nesne deposunu temizler. Kurulu uygulamalar çalışmaya devam eder. + Uygulamayı (%1$s) ve başka hiçbir şeyin kullanmadığı çalışma zamanlarını kaldırır. Ev klasörünüzdeki verileri kalır. %d paket %d paket diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 3f7cf70c26..0fe47636a7 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -1429,6 +1429,14 @@ Чорне тло, білий текст і синій для всього вибраного, у фокусі чи натиснутого. Електричний темно-синій Яскравіший синій на поверхнях із темно-синім відтінком замість сірого. + Градієнт + Ваші основний і додатковий кольори, що плавно переходять на кнопках і виділеннях. + Основний + Додатковий + Відтінок + Насиченість + Яскравість + Колір hex Esc Ins Del @@ -2546,6 +2554,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 572d7e9435..c7e88e0653 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -1387,6 +1387,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 @@ -2471,6 +2479,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 aa0b896513..68d927ebb2 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1465,6 +1465,14 @@ 黑色背景、白色文字,选中、聚焦或按下的元素使用蓝色。 电光藏青 更明亮的蓝色,配以偏藏青而非灰色的界面。 + 渐变 + 你自己选择的主色和辅色,在按钮和高亮处渐变呈现。 + 主色 + 辅色 + 色相 + 饱和度 + 亮度 + 十六进制颜色 Esc Ins Del @@ -1874,6 +1882,7 @@ 不是 Adreno GPU 受支持 实验性:其驱动为测试构建 + Adreno 850 实验支持:需要配套的实验版显示驱动和游戏驱动;尚未在此设备上验证 低于已测试的硬件(Adreno 725 及更新):可能无法运行 不受支持:DroidDeck 需要 Adreno(骁龙)GPU @@ -2473,6 +2482,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 78096f4b65..a39c7b101d 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -1389,6 +1389,14 @@ 黑色背景、白色文字,所有已選取、焦點所在或按下的項目都使用藍色。 電光海軍藍 更明亮的藍色,搭配偏海軍藍而非灰色的介面。 + 漸層 + 你自行選擇的主色與輔色,在按鈕與強調處以漸層呈現。 + 主色 + 輔色 + 色相 + 飽和度 + 亮度 + 十六進位色彩 Esc Ins Del @@ -1798,6 +1806,7 @@ 不是 Adreno GPU 受支援 實驗性:其驅動程式為測試版本 + Adreno 850 實驗性支援:需要相容的實驗版顯示驅動程式及遊戲驅動程式;尚未在此裝置上驗證 低於已測試的硬件(Adreno 725 或更新):可能無法執行 不受支援:DroidDeck 需要 Adreno (Snapdragon) GPU @@ -2473,6 +2482,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 dd52624c53..d29f3cef46 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -1389,6 +1389,14 @@ 黑色背景、白色文字,選取、聚焦或按下的項目使用藍色。 電光藏青 更亮的藍色,搭配偏藏青而非灰色的介面。 + 漸層 + 你自行選擇的主色與輔色,在按鈕與強調處以漸層呈現。 + 主色 + 輔色 + 色相 + 飽和度 + 亮度 + 十六進位色彩 Esc Ins Del @@ -1798,6 +1806,7 @@ 不是 Adreno GPU 受支援 實驗性:其驅動程式為測試版本 + Adreno 850 實驗性支援:需要相容的實驗版顯示驅動程式及遊戲驅動程式;尚未在此裝置上驗證 低於已測試的硬體(Adreno 725 及更新機型):可能無法執行 不受支援:DroidDeck 需要 Adreno(Snapdragon)GPU @@ -2473,6 +2482,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 09f84d9b88..c449a05be5 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1207,6 +1207,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. @@ -1456,6 +1458,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 @@ -1883,6 +1893,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 @@ -2627,6 +2638,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/core/DownloaderResumeTest.kt b/app/src/test/java/com/droiddeck/launcher/core/DownloaderResumeTest.kt index a3faef0701..73fd0161c6 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/DownloaderResumeTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/DownloaderResumeTest.kt @@ -167,4 +167,10 @@ class DownloaderResumeTest { assertEquals(listOf(catalog), DownloadSource.candidates(catalog)) } + + @Test fun withoutADigestOnlyTheOriginalUrlIsTried() { + val url = "https://github.com/owner/repo/releases/download/v1/app.AppImage" + assertEquals(listOf(url), Downloader.sources(url, null)) + assertEquals(DownloadSource.candidates(url), Downloader.sources(url, "a".repeat(64))) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/core/LogRedactorTest.kt b/app/src/test/java/com/droiddeck/launcher/core/LogRedactorTest.kt index ddeb3ac1fa..a67093e935 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/LogRedactorTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/LogRedactorTest.kt @@ -37,6 +37,83 @@ class LogRedactorTest { assertEquals("login ok", LogRedactor.redact("login someone@example.com ok")) } + @Test fun onlyLoaderDiagnosticsKeepHidlSharedLibraryNames() { + val library = "android.hardware.graphics.mapper@4.0.so" + val line = "dlopen failed: library \"$library\" not found" + val pathLine = "dlopen failed: library \"/vendor/lib64/hw/$library\" not found" + + assertEquals(line, LogRedactor.redact(line)) + assertEquals(line, LogRedactor.redactForShare(line)) + assertEquals(pathLine, LogRedactor.redact(pathLine)) + assertEquals(pathLine, LogRedactor.redactForShare(pathLine)) + } + + @Test fun privacyRulesOverrideTheHidlSharedLibraryException() { + val library = "android.hardware.graphics.mapper@4.0.so" + assertEquals("token=", LogRedactor.redact("token=$library")) + assertEquals("username=", LogRedactor.redact("username=$library")) + assertEquals("{\"password\":\"\"}", LogRedactor.redact("{\"password\":\"$library\"}")) + assertEquals("{\"password\":\"\"}", LogRedactor.redactForShare("{\"password\":\"$library\"}")) + assertEquals("{\"password\":\"\"}", LogRedactor.redact("{\"password\":\"don't-use-$library\"}")) + assertEquals("{\"password\":\"\"}", LogRedactor.redactForShare("{\"password\":\"don't-use-$library\"}")) + + val mixed = "dlopen failed: library \"$library\" not found; token=abcdef123456; contact=alice!$library; {\"password\":\"library \\\"$library\\\" not found\"}" + val expected = "dlopen failed: library \"$library\" not found; token=; contact=alice!; {\"password\":\"\"}" + assertEquals(expected, LogRedactor.redact(mixed)) + assertEquals(expected, LogRedactor.redactForShare(mixed)) + + val root = java.nio.file.Files.createTempDirectory("hidl-redactor").toFile() + val users = java.io.File(root, "loginusers.vdf") + users.writeText("\"AccountName\" \"$library\"") + try { + LogRedactor.learnAccounts(users) + assertEquals("", LogRedactor.redact(library)) + } finally { + LogRedactor.learnAccounts() + root.deleteRecursively() + } + } + + @Test fun hidlSharedLibraryNamesAreRedactedOutsideLoaderDiagnostics() { + val library = "android.hardware.graphics.mapper@4.0.so" + + assertEquals("", LogRedactor.redact(library)) + assertEquals("", LogRedactor.redactForShare(library)) + assertEquals("/vendor/lib64/hw/", LogRedactor.redact("/vendor/lib64/hw/$library")) + for (punctuation in listOf("!", "#", "~", "/", "=")) { + val expected = "contact=alice$punctuation" + assertEquals(expected, LogRedactor.redact("contact=alice$punctuation$library")) + assertEquals(expected, LogRedactor.redactForShare("contact=alice$punctuation$library")) + } + assertEquals("", LogRedactor.redact("$library.evil")) + assertEquals("", LogRedactor.redact("someone@company.so")) + assertEquals("", LogRedactor.redact("not$library")) + assertEquals("_debug", LogRedactor.redact("${library}_debug")) + assertEquals(".1", LogRedactor.redact("${library}.1")) + assertEquals("@attacker", LogRedactor.redact("${library}@attacker")) + assertEquals("", LogRedactor.redact("android.hardware.graphics.mapper@4.0.software")) + assertEquals("", LogRedactor.redact("android.hardware.graphics.mapper@4.0.so.evil")) + } + + @Test fun loaderContextRequiresExactWordsAndABoundedAndroidPath() { + val library = "android.hardware.graphics.mapper@4.0.so" + val valid = "library \"/system/lib64/$library\" not found: needed by app" + assertEquals(valid, LogRedactor.redact(valid)) + assertEquals(valid, LogRedactor.redactForShare(valid)) + for (line in listOf( + "not_library \"$library\" not found", + "library \"$library\" not found_suffix", + "library \"/home/user/$library\" not found", + "library \"relative/$library\" not found", + "library \"/vendor/invalid!/$library\" not found", + "library \"/vendor/" + "a/".repeat(2050) + "$library\" not found", + )) { + val expected = line.replace(library, "") + assertEquals(expected, LogRedactor.redact(line)) + assertEquals(expected, LogRedactor.redactForShare(line)) + } + } + @Test fun clockTimeIsNotAnAddress() { val line = "[2026-09-27 10:03:05] Startup" assertEquals(line, LogRedactor.redact(line)) 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/runtime/DesktopRemovalTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/DesktopRemovalTest.kt new file mode 100644 index 0000000000..250a655354 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/DesktopRemovalTest.kt @@ -0,0 +1,122 @@ +package com.droiddeck.launcher.runtime + +import android.content.ContextWrapper +import com.droiddeck.launcher.BuildConfig +import java.io.File +import java.nio.file.Files +import java.nio.file.Paths +import java.util.zip.GZIPInputStream +import org.junit.After +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment + +@RunWith(RobolectricTestRunner::class) +class DesktopRemovalTest { + private val dir = Files.createTempDirectory("desktop-removal").toFile() + private val context = object : ContextWrapper(RuntimeEnvironment.getApplication()) { + override fun getFilesDir() = File(dir, "files").apply { mkdirs() } + override fun getCacheDir() = File(dir, "cache").apply { mkdirs() } + } + private val root = LinuxRuntime.rootDir(context).apply { mkdirs() } + private val marker = File(root, ".droiddeck-pkg-${DesktopCatalog.DESKTOP_ID}") + private val journal = File(root, marker.name + ".installing") + private val pending = File(root, DesktopRemoval.PENDING) + private val listener = LinuxRuntimeInstaller.ProgressListener { _, _ -> } + + @After fun cleanup() { dir.deleteRecursively() } + + @Test fun removesTheDesktopWhileKeepingRuntimeAppsGamesAndSettings() { + val desktop = desktopFiles() + marker.writeText(BuildConfig.DESKTOP_KDE_TAG) + val keep = listOf("root/.local/share/Steam/steamapps/common/game/data", "root/.config/kdeglobals", + "opt/appimages/custom.AppImage", "usr/lib/shared.so", "usr/share/plasma/custom") + .map { file(it, "keep") } + + assertTrue(DesktopCatalog.desktopPresent(context)) + assertNull(DesktopCatalog.removeDesktop(context, listener)) + + assertFalse(Files.exists(desktop.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)) + keep.forEach { assertEquals("keep", it.readText()) } + assertFalse(DesktopCatalog.desktopPresent(context)) + assertFalse(DesktopCatalog.desktopInstalled(context)) + } + + @Test fun interruptedInstallCanBeRemovedWithoutBeingResumedAtTheNextLaunch() { + desktopFiles() + val entry = DesktopCatalog.desktopEntry(context) + journal.writeText(DesktopCatalog.entryJson(entry).toString()) + val download = File(context.cacheDir, "pkg-${entry.id}-${entry.sha256.take(12)}.download").apply { writeText("download") } + val resume = File(download.path + ".resume.properties").apply { writeText("resume") } + val unrelated = file(".droiddeck-pkg-emulators.installing", DesktopCatalog.entryJson(DesktopCatalog.Entry( + "emulators", "Emulators", 1, "1", "tar", "https://example.invalid/emulators", "a".repeat(64), 1L, "", "", "", + )).toString()) + assertTrue(DesktopCatalog.desktopPresent(context)) + + assertNotNull(DesktopCatalog.removeDesktop(context) { _, _ -> error("interrupted") }) + assertTrue(pending.exists()) + assertTrue(journal.exists()) + assertTrue(DesktopCatalog.desktopPresent(context)) + assertNull(DesktopCatalog.removeDesktop(context, listener)) + + assertFalse(journal.exists()) + assertFalse(pending.exists()) + assertFalse(download.exists()) + assertFalse(resume.exists()) + assertFalse(DesktopCatalog.desktopPresent(context)) + assertEquals(listOf("emulators"), DesktopCatalog.interrupted(context).map { it.id }) + assertTrue(unrelated.exists()) + } + + @Test fun refusesUnknownDesktopVersionsAndMissingRuntimeOwnershipBeforeDeletingAnything() { + val desktop = desktopFiles() + marker.writeText("future-desktop") + assertNotNull(DesktopCatalog.removeDesktop(context, listener)) + assertEquals("future-desktop", marker.readText()) + marker.writeText(BuildConfig.DESKTOP_KDE_TAG) + journal.writeText(DesktopCatalog.entryJson(DesktopCatalog.desktopEntry(context)).put("version", "future-desktop").toString()) + assertNotNull(DesktopCatalog.removeDesktop(context, listener)) + assertTrue(journal.exists()) + journal.delete() + File(root, "var/lib/pacman/local/base-1/files").delete() + assertNotNull(DesktopCatalog.removeDesktop(context, listener)) + assertEquals(BuildConfig.DESKTOP_KDE_TAG, marker.readText()) + assertFalse(pending.exists()) + assertTrue(Files.isSymbolicLink(desktop.toPath())) + } + + @Test fun failedDownloadCleanupKeepsTheInstallRecordSoRemovalCanRetry() { + val entry = DesktopCatalog.desktopEntry(context) + val download = File(context.cacheDir, "pkg-${entry.id}-${entry.sha256.take(12)}.download") + for (blocked in listOf(download, File(download.path + ".resume.properties"))) { + desktopFiles() + journal.writeText(DesktopCatalog.entryJson(entry).toString()) + blocked.mkdirs() + val blocker = File(blocked, "blocker").apply { writeText("fixture") } + + assertNotNull(DesktopCatalog.removeDesktop(context, listener)) + assertTrue(journal.exists()) + assertTrue(pending.exists()) + assertTrue(blocker.delete()) + assertNull(DesktopCatalog.removeDesktop(context, listener)) + assertFalse(blocked.exists()) + assertFalse(journal.exists()) + assertFalse(pending.exists()) + } + } + + private fun file(path: String, text: String) = File(root, path).apply { parentFile!!.mkdirs(); writeText(text) } + + private fun desktopFiles(): File { + file("var/lib/pacman/local/base-1/files", "%FILES%\nusr/lib/shared.so\n") + val entry = GZIPInputStream(context.assets.open("desktop-removal/kde-remove.tsv.gzip")).bufferedReader().use { reader -> + reader.lineSequence().map(DesktopFileRemoval.Entry::parse).first { it.kind == "L" && it.path.startsWith("usr/") } + } + return File(root, entry.path).apply { + parentFile!!.mkdirs() + Files.createSymbolicLink(toPath(), Paths.get(entry.identity)) + } + } +} 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 3f3fbf07f8..e73905cbe6 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) @@ -45,6 +46,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/DesktopUninstallTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt new file mode 100644 index 0000000000..3f76cac3ba --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt @@ -0,0 +1,101 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onLast +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], qualifiers = "w1200dp-h752dp-land", application = android.app.Application::class) +class DesktopUninstallTest { + @get:Rule val compose = createRobolectricComposeRule() + private var removals = 0 + private var runtimeBlocked by mutableStateOf(false) + + @After fun closeConfirmation() { Steps.drop() } + + @Test fun uninstallIsAvailableOnTheDesktopPageAndRequiresConfirmation() { + show() + compose.onNodeWithText("Open desktop").assertIsDisplayed() + compose.onNodeWithText("Uninstall").assertIsDisplayed().performClick() + settle() + assertEquals(0, removals) + compose.onNodeWithText("Uninstall the desktop?").assertIsDisplayed() + compose.onAllNodesWithText("Uninstall").onLast().performClick() + assertEquals(1, removals) + } + + @Test fun uninstallIsDisabledWhileRuntimeChangesAreBlocked() { + show(blocked = true) + compose.onNodeWithText("Uninstall").assertIsNotEnabled() + } + + @Test fun aPartialDesktopStillOffersUninstall() { + show(installed = false) + compose.onNodeWithText("Uninstall").assertIsDisplayed() + } + + @Test fun anUninstalledDesktopNoLongerOffersUninstall() { + show(installed = false, present = false) + compose.onNodeWithText("Uninstall").assertDoesNotExist() + } + + @Test fun startingRuntimeWorkWhileConfirmingDisablesUninstall() { + show() + compose.onNodeWithText("Uninstall").performClick() + settle() + compose.runOnIdle { runtimeBlocked = true } + settle() + compose.onAllNodesWithText("Uninstall").onLast().assertIsNotEnabled() + assertEquals(0, removals) + } + + private fun settle() = compose.mainClock.advanceTimeBy(2_000) + + private fun show(installed: Boolean = true, blocked: Boolean = false, present: Boolean = true) { + runtimeBlocked = blocked + compose.mainClock.autoAdvance = false + compose.setContent { + DroidDeckTheme { + CompositionLocalProvider(LocalFrontFocus provides FrontFocus()) { + FocusGlideHost { + Box(Modifier.fillMaxSize()) { + DesktopPage(FrontEndState( + installed = "r9", ready = true, available = null, busy = false, stage = "", percent = -1, + desktopInstalled = installed, desktopPresent = present, runtimeActionsBlocked = runtimeBlocked, + offlineAccount = null, offline = false, frameGenLabel = "", romsDir = null, logsEnabled = false, + steamGames = emptyList(), emulators = emptyList(), running = null, + ), 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 = { _, _ -> }, onRemoveDesktop = { removals++ }, + ), Modifier.fillMaxSize(), onSelect = {}) + StepsLayer(Offset.Zero) + } + } + } + } + } + settle() + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/DialogSemanticsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/DialogSemanticsTest.kt new file mode 100644 index 0000000000..c08c0f2341 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/DialogSemanticsTest.kt @@ -0,0 +1,42 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.animation.core.MutableTransitionState +import androidx.compose.material3.Text +import androidx.compose.runtime.remember +import androidx.compose.ui.test.assertHasNoClickAction +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import org.junit.Assert.assertEquals +import org.junit.Rule +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 DialogSemanticsTest { + @get:Rule val compose = createRobolectricComposeRule() + + @Test fun dialogTextNodesStaySeparateAndNonClickableInMergedSemanticsTree() { + var closed = 0 + compose.setContent { + DroidDeckTheme { + val shown = remember { MutableTransitionState(true) } + AppDialog(shown = shown, close = { closed++ }, label = "testDialog", wide = false) { + Text("Dialog Title") + Text("Dialog Hint") + Text("Body Copy") + } + } + } + compose.onNodeWithText("Dialog Title").assertExists().assertHasNoClickAction() + compose.onNodeWithText("Dialog Hint").assertExists().assertHasNoClickAction() + compose.onNodeWithText("Body Copy").assertExists().assertHasNoClickAction() + + compose.onNodeWithText("Dialog Title").performClick() + compose.onNodeWithText("Body Copy").performClick() + compose.waitForIdle() + assertEquals(0, closed) + } +} 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/SessionSecondScreenTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt new file mode 100644 index 0000000000..04d3f5632b --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt @@ -0,0 +1,158 @@ +package com.droiddeck.launcher.ui + +import android.hardware.display.DisplayManager +import android.hardware.input.InputManager +import android.view.Display +import android.view.InputDevice +import android.view.KeyEvent +import android.view.View +import android.view.ViewGroup +import android.widget.Button +import androidx.compose.ui.test.* +import androidx.compose.runtime.MutableState +import com.droiddeck.launcher.R +import com.droiddeck.launcher.SessionActivity +import com.droiddeck.launcher.gpu.FrameGen +import com.droiddeck.launcher.gpu.Lossless +import com.droiddeck.launcher.input.SecondScreenDisplay +import com.droiddeck.launcher.input.SecondScreenMode +import com.droiddeck.launcher.input.PadBridgeRoutingTest +import com.droiddeck.launcher.session.SessionService +import com.droiddeck.launcher.session.SessionState +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode +import org.robolectric.shadows.InputDeviceBuilder +import org.robolectric.util.ReflectionHelpers + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], qualifiers = "w800dp-h600dp") +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class SessionSecondScreenTest { + @get:Rule val compose = createRobolectricComposeRule() + private val context get() = RuntimeEnvironment.getApplication() + private var previousMode = "" + private var previousDeckPad = false + + @Before fun setUp() { + previousMode = SessionState.mode + previousDeckPad = SessionState.deckPad + SessionState.deckPad = false + } + + @After fun tearDown() { + SessionState.mode = previousMode + SessionState.deckPad = previousDeckPad + } + + @Test fun desktopMenuOffersTheExistingTrackpadAndTerminal() = checkModes(steam = false) + + @Test fun steamMenuKeepsTheExistingTrackpadAndTerminal() = checkModes(steam = true) + + @Test fun desktopWithoutASecondDisplayFallsBackToController() { + SessionState.mode = SessionService.MODE_DESKTOP + var page = SessionDrawerPage.SECOND_SCREEN + compose.setContent { + DroidDeckTheme { + SessionDrawer(true, page, false, { page = it }, actions(false, emptyList())) + } + } + compose.runOnIdle { assertEquals(SessionDrawerPage.CONTROLLER, page) } + compose.onNodeWithText(context.getString(R.string.second_mode_keyboard_trackpad)).assertDoesNotExist() + } + + @Test fun desktopTrackpadOmitsSteamShortcuts() = checkShortcuts(steam = false) + + @Test fun steamTrackpadKeepsWorkingSteamShortcuts() = checkShortcuts(steam = true) + + @Test + @Config(sdk = [34], shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class]) + fun controllerBumpersReachTheSecondScreenInBothSessionModes() { + val device = InputDeviceBuilder.newBuilder().setId(42).setName("Second screen test pad") + .setDescriptor("second-screen-pad").setExternal(true).setSources(InputDevice.SOURCE_GAMEPAD).build() + shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device) + for (mode in listOf(SessionService.MODE_DESKTOP, SessionService.MODE_STEAM)) { + SessionState.mode = mode + val activity = Robolectric.buildActivity(SessionActivity::class.java).get() + fun state(name: String): MutableState = ReflectionHelpers.getField(activity, "$name\$delegate") + state("drawerOpen").value = true + state("drawerControllerActive").value = true + state>("secondScreenDisplays").value = listOf(SecondScreenDisplay(1, "Bottom screen")) + for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.SECOND_SCREEN, + KeyEvent.KEYCODE_BUTTON_L1 to SessionDrawerPage.CONTROLLER)) { + assertTrue(activity.dispatchKeyEvent(KeyEvent(0L, 0L, KeyEvent.ACTION_DOWN, button, 0, 0, + device.id, 0, 0, InputDevice.SOURCE_GAMEPAD))) + assertEquals(page, state("drawerPage").value) + } + } + } + + private fun checkModes(steam: Boolean) { + SessionState.mode = if (steam) SessionService.MODE_STEAM else SessionService.MODE_DESKTOP + val selected = mutableListOf() + val displays = listOf(SecondScreenDisplay(1, "Bottom screen")) + compose.setContent { + DroidDeckTheme { + SessionDrawer(true, SessionDrawerPage.SECOND_SCREEN, false, {}, actions(steam, displays) { selected += it }) + } + } + for (mode in listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL)) { + compose.onNodeWithText(context.getString(mode.label)).performScrollTo().assertIsDisplayed().performClick() + } + compose.onNodeWithText(context.getString(SecondScreenMode.DECK_CONTROLS.label)).assertDoesNotExist() + assertEquals(listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL), selected) + } + + private fun checkShortcuts(steam: Boolean) { + SessionState.mode = if (steam) SessionService.MODE_STEAM else SessionService.MODE_DESKTOP + val activity = Robolectric.buildActivity(SessionActivity::class.java).get() + val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY) + var menus = 0 + var qams = 0 + val panel = SecondScreenPresentation(activity, display, { _, _, _, _ -> }, { _, _ -> }, {}, + { menus++ }, { qams++ }, {}) + try { + panel.create() + panel.showMode(SecondScreenMode.KEYBOARD_TRACKPAD) + val buttons = descendants(panel.window!!.decorView).filterIsInstance