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/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/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt index 4e455d3c1d..abc1eee8f0 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -1622,6 +1622,7 @@ class MainActivity : ComponentActivity() { pipAutoEnter = pipAutoEnter, unfoldedControls = if (mode == SessionService.MODE_STEAM && com.droiddeck.launcher.session.SessionDisplay.foldable(this)) unfoldedControls else null, + unfoldedControlsWithController = unfoldedControlsWithController, oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null, backActionsInverted = backActionsInverted, directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null, @@ -1688,6 +1689,9 @@ class MainActivity : ComponentActivity() { onZramCompression = { on -> SessionPrefs.setZramCompression(this, on); zramCompression = on }, onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this, on); pipAutoEnter = on }, onUnfoldedControls = { on -> SessionPrefs.setUnfoldedControls(this, on); unfoldedControls = on }, + onUnfoldedControlsWithController = { on -> + SessionPrefs.setUnfoldedControlsWithController(this, on); unfoldedControlsWithController = on + }, onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o }, onBackActionsInverted = { inverted -> SessionPrefs.setBackActionsInverted(this, inverted) @@ -1876,10 +1880,12 @@ class MainActivity : ComponentActivity() { private var pipAutoEnter by mutableStateOf(false) private var unfoldedControls by mutableStateOf(false) + private var unfoldedControlsWithController by mutableStateOf(false) private fun loadModeSettings(mode: String) { pipAutoEnter = SessionPrefs.pipAutoEnter(this) unfoldedControls = SessionPrefs.unfoldedControls(this) + unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this) resolution = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) fexPreset = SessionPrefs.fexPreset(this) forceSsbs = SessionPrefs.forceSsbs(this) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index ace8b51f28..6de07a00dc 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -134,6 +134,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private var pipUi by mutableStateOf(false) private var pipAutoEnter by mutableStateOf(false) private var unfoldedControls by mutableStateOf(false) + private var unfoldedControlsWithController by mutableStateOf(false) private var picturePosition by mutableStateOf("center") private fun applyGameAlignment() { @@ -366,17 +367,46 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private var secondScreenDisplays by mutableStateOf>(emptyList()) private var selectedSecondScreenDisplay by mutableStateOf(SessionState.secondScreenDisplay) private var started = false + private var sessionActivityDisplayId = Display.DEFAULT_DISPLAY private lateinit var displayManager: DisplayManager private var secondScreenPresentation: SecondScreenPresentation? = null private val displayListener = object : DisplayManager.DisplayListener { - override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays() - override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays() + override fun onDisplayAdded(displayId: Int) { + notifyActivityDisplayStateChanged(displayId) + refreshSecondScreenDisplays() + } + override fun onDisplayRemoved(displayId: Int) { + if (refreshActivityDisplayId() && started) { + SessionService.setActivityDisplay(this@SessionActivity, sessionActivityDisplayId) + } + refreshSecondScreenDisplays() + } override fun onDisplayChanged(displayId: Int) { + notifyActivityDisplayStateChanged(displayId) followPanelRefresh(displayId) refreshSecondScreenDisplays() } } + @Suppress("DEPRECATION") + private fun currentActivityDisplayId(): Int = windowManager.defaultDisplay.displayId + + private fun refreshActivityDisplayId(): Boolean { + val current = if (Build.VERSION.SDK_INT >= 30) display?.displayId ?: currentActivityDisplayId() + else currentActivityDisplayId() + val changed = sessionActivityDisplayId != current + sessionActivityDisplayId = current + SessionState.activityDisplayId = current + return changed + } + + private fun notifyActivityDisplayStateChanged(changedDisplayId: Int) { + val changed = refreshActivityDisplayId() + if (started && (changed || changedDisplayId == sessionActivityDisplayId)) { + SessionService.setActivityDisplay(this, sessionActivityDisplayId) + } + } + private fun followPanelRefresh(displayId: Int) { if (!CompositorHost.isStarted) return val output = glassesScreen?.display @@ -923,6 +953,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { }, unfoldedControls = if (com.droiddeck.launcher.session.SessionDisplay.foldable(this@SessionActivity)) unfoldedControls else null, onUnfoldedControls = ::chooseUnfoldedControls, + unfoldedControlsWithController = unfoldedControlsWithController, + onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController, onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) }, onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() }, onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() }, @@ -1407,6 +1439,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun readPrefs() { pipAutoEnter = SessionPrefs.pipAutoEnter(this) unfoldedControls = SessionPrefs.unfoldedControls(this) + unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this) picturePosition = SessionPrefs.picturePosition(this) hudOn = SessionPrefs.hudEnabled(this) hudFps = SessionPrefs.hudShowFps(this) @@ -1678,7 +1711,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { intent.getStringExtra(SessionService.EXTRA_STEAM_UI), intent.getStringExtra(SessionService.EXTRA_STEAM_URL), intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS), - shownOnDisplayId, + sessionActivityDisplayId, ) } applyFrameGen() @@ -1729,7 +1762,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onConfigurationChanged(newConfig: android.content.res.Configuration) { super.onConfigurationChanged(newConfig) - if (started) SessionService.setActivityDisplay(this, shownOnDisplayId) + if (refreshActivityDisplayId() && started) { + SessionService.setActivityDisplay(this, sessionActivityDisplayId) + } cancelTouchGestures() applyFollowOrientation(newConfig) applyUnfoldedControls() @@ -2456,6 +2491,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { applyUnfoldedControls() } + private fun chooseUnfoldedControlsWithController(on: Boolean) { + SessionPrefs.setUnfoldedControlsWithController(this, on) + unfoldedControlsWithController = on + applyUnfoldedControls() + } + private fun refreshControls() { applyUnfoldedControls() updateOnScreenControls() @@ -2465,11 +2506,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (!::sessionRoot.isInitialized) return val width = sessionRoot.width val height = sessionRoot.height - val wanted = unfoldedControls && com.droiddeck.launcher.session.SessionDisplay.foldable(this) && - !PadBridge.anyControllerConnected() && !SteamControllerBle.connected && - SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad && - !pipUi && !isInPictureInPictureMode && width > 0 && height > 0 && - resources.configuration.smallestScreenWidthDp >= com.droiddeck.launcher.session.SessionDisplay.UNFOLDED_MIN_DP + val wanted = com.droiddeck.launcher.session.SessionDisplay.unfoldedControlsWanted( + enabled = unfoldedControls, + foldable = com.droiddeck.launcher.session.SessionDisplay.foldable(this), + controllerConnected = PadBridge.anyControllerConnected() || SteamControllerBle.connected, + keepWithController = unfoldedControlsWithController, + steamDeckPad = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad, + pip = pipUi || isInPictureInPictureMode, + width = width, + height = height, + smallestWidthDp = resources.configuration.smallestScreenWidthDp, + ) val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height) else FrameLayout.LayoutParams.MATCH_PARENT val params = surfaceView.layoutParams as FrameLayout.LayoutParams @@ -2888,11 +2935,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { super.onStart() if (runtimeRemovalBlocked) return started = true + refreshActivityDisplayId() displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper())) refreshSecondScreenDisplays() if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode) startedScreens++ - SessionService.setActivityVisible(this, true, shownOnDisplayId) + SessionService.setActivityVisible(this, true, sessionActivityDisplayId) Glasses.rescan() updateGlassesScreen() updateHandCamera() @@ -2906,7 +2954,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { closeSecondScreen(reset = false) startedScreens = (startedScreens - 1).coerceAtLeast(0) updateGlassesScreen() - if (startedScreens == 0) SessionService.setActivityVisible(this, false) + if (startedScreens == 0) SessionService.setActivityVisible(this, false, sessionActivityDisplayId) super.onStop() } @@ -2937,6 +2985,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onResume() { super.onResume() + if (refreshActivityDisplayId() && started) { + SessionService.setActivityDisplay(this, sessionActivityDisplayId) + } applyFollowOrientation(resources.configuration) if (runtimeRemovalBlocked) return com.droiddeck.launcher.ui.Motion.refresh(this) 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/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 cd0a750aca..07a3c9f9e6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -989,6 +989,13 @@ object SessionPrefs { prefs(context).edit().putBoolean("unfoldedControls", enabled).apply() } + fun unfoldedControlsWithController(context: Context): Boolean = + prefs(context).getBoolean("unfoldedControlsWithController", false) + + fun setUnfoldedControlsWithController(context: Context, enabled: Boolean) { + prefs(context).edit().putBoolean("unfoldedControlsWithController", enabled).apply() + } + const val SURFACE_STICK = "stick" const val SURFACE_TRACKPAD = "trackpad" 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 fd9d772701..55e1adb440 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -76,9 +76,16 @@ class SessionService : Service() { private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL private var steamDownloadsInBackground = false private var activityVisible = true + private var activityDisplayId = Display.DEFAULT_DISPLAY private var xrActivityVisible = false private var signInHold = false - private val hasVisibleSurface get() = sessionHasVisibleSurface(activityVisible || signInHold, screenOn, xrActivityVisible) + private val hasVisibleSurface get() = !SessionVisibilityPolicy.isHidden( + activityStarted = activityVisible || signInHold, + defaultDisplayOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn, + activityOnDefaultDisplay = activityDisplayId == Display.DEFAULT_DISPLAY, + activityDisplayOn = activityDisplayOn(), + xrActivityVisible = xrActivityVisible, + ) private var screenOn = true private var sessionDisplayId = Display.DEFAULT_DISPLAY private var manualPauseRequested = false @@ -115,12 +122,22 @@ class SessionService : Service() { private val displayListener = object : DisplayManager.DisplayListener { override fun onDisplayAdded(displayId: Int) {} override fun onDisplayRemoved(displayId: Int) { - if (displayId != sessionDisplayId) return - sessionDisplayId = Display.DEFAULT_DISPLAY - refreshScreenOn() + if (displayId == sessionDisplayId) { + sessionDisplayId = Display.DEFAULT_DISPLAY + refreshScreenOn() + } + if (displayId == activityDisplayId) { + suspendAttemptFailed = false + updateSuspendPolicy() + } } override fun onDisplayChanged(displayId: Int) { if (displayId == sessionDisplayId && displayId != Display.DEFAULT_DISPLAY) refreshScreenOn() + if (displayId == activityDisplayId) { + resumeSteamSleepOnReturn() + suspendAttemptFailed = false + updateSuspendPolicy() + } } } @@ -132,6 +149,14 @@ class SessionService : Service() { interactive ?: (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: true, state) } + private fun activityDisplayOn(): Boolean { + if (activityDisplayId == Display.DEFAULT_DISPLAY) { + return (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn + } + val displays = getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager ?: return false + return displays.getDisplay(activityDisplayId)?.state == Display.STATE_ON + } + private fun refreshScreenOn() { val on = readScreenOn() if (on == screenOn) return @@ -202,6 +227,7 @@ class SessionService : Service() { ACTION_ACTIVITY_VISIBLE -> { if (!SessionState.pipActive) pipTask = false activityVisible = true + activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId) sessionDisplayId = intent.getIntExtra(EXTRA_DISPLAY_ID, sessionDisplayId) screenOn = readScreenOn() suspendDownloadNow = false @@ -215,8 +241,16 @@ class SessionService : Service() { refreshScreenOn() return START_NOT_STICKY } + ACTION_ACTIVITY_DISPLAY_CHANGED -> { + activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId) + resumeSteamSleepOnReturn() + suspendAttemptFailed = false + updateSuspendPolicy() + return START_NOT_STICKY + } ACTION_ACTIVITY_HIDDEN -> { activityVisible = false + activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId) suspendAttemptFailed = false updateSuspendPolicy() return START_NOT_STICKY @@ -279,6 +313,7 @@ class SessionService : Service() { xrActivityVisible = false signInHold = false sessionDisplayId = intent?.getIntExtra(EXTRA_DISPLAY_ID, Display.DEFAULT_DISPLAY) ?: Display.DEFAULT_DISPLAY + activityDisplayId = intent?.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, sessionDisplayId) ?: sessionDisplayId screenOn = readScreenOn() manualPauseRequested = false suspendDownloadNow = false @@ -1842,7 +1877,9 @@ class SessionService : Service() { private const val ACTION_ACTIVITY_VISIBLE = "com.droiddeck.launcher.ACTIVITY_VISIBLE" private const val ACTION_ACTIVITY_HIDDEN = "com.droiddeck.launcher.ACTIVITY_HIDDEN" private const val ACTION_ACTIVITY_DISPLAY = "com.droiddeck.launcher.ACTIVITY_DISPLAY" + private const val ACTION_ACTIVITY_DISPLAY_CHANGED = "com.droiddeck.launcher.ACTIVITY_DISPLAY_CHANGED" private const val EXTRA_DISPLAY_ID = "displayId" + private const val EXTRA_ACTIVITY_DISPLAY_ID = "activityDisplayId" private const val ACTION_XR_ACTIVITY_VISIBLE = "com.droiddeck.launcher.XR_ACTIVITY_VISIBLE" private const val ACTION_XR_ACTIVITY_HIDDEN = "com.droiddeck.launcher.XR_ACTIVITY_HIDDEN" private const val ACTION_SIGN_IN_HOLD = "com.droiddeck.launcher.SIGN_IN_HOLD" @@ -1887,8 +1924,10 @@ class SessionService : Service() { steamUi: String? = null, steamUrl: String? = null, programArgs: Array? = null, displayId: Int = Display.DEFAULT_DISPLAY, ) { + SessionState.activityDisplayId = displayId val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode) .putExtra(EXTRA_DISPLAY_ID, displayId) + .putExtra(EXTRA_ACTIVITY_DISPLAY_ID, displayId) if (program != null) intent.putExtra(EXTRA_PROGRAM, program) if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs) if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi) @@ -1909,15 +1948,29 @@ class SessionService : Service() { context.startService(Intent(context, SessionService::class.java).setAction(ACTION_PIP_BEGIN)) } - fun setActivityVisible(context: Context, visible: Boolean, displayId: Int = Display.DEFAULT_DISPLAY) { + fun setActivityVisible(context: Context, visible: Boolean, displayId: Int = contextDisplayId(context)) { if (!SessionState.running) return val action = if (visible) ACTION_ACTIVITY_VISIBLE else ACTION_ACTIVITY_HIDDEN - context.startService(Intent(context, SessionService::class.java).setAction(action).putExtra(EXTRA_DISPLAY_ID, displayId)) + SessionState.activityDisplayId = displayId + context.startService(Intent(context, SessionService::class.java).setAction(action) + .putExtra(EXTRA_DISPLAY_ID, displayId) + .putExtra(EXTRA_ACTIVITY_DISPLAY_ID, displayId)) } fun setActivityDisplay(context: Context, displayId: Int) { if (!SessionState.running) return - context.startService(Intent(context, SessionService::class.java).setAction(ACTION_ACTIVITY_DISPLAY).putExtra(EXTRA_DISPLAY_ID, displayId)) + SessionState.activityDisplayId = displayId + context.startService(Intent(context, SessionService::class.java).setAction(ACTION_ACTIVITY_DISPLAY) + .putExtra(EXTRA_DISPLAY_ID, displayId)) + context.startService(Intent(context, SessionService::class.java).setAction(ACTION_ACTIVITY_DISPLAY_CHANGED) + .putExtra(EXTRA_ACTIVITY_DISPLAY_ID, displayId)) + } + + @Suppress("DEPRECATION") + private fun contextDisplayId(context: Context): Int { + val activity = context as? android.app.Activity ?: return Display.DEFAULT_DISPLAY + return if (Build.VERSION.SDK_INT >= 30) activity.display?.displayId ?: activity.windowManager.defaultDisplay.displayId + else activity.windowManager.defaultDisplay.displayId } fun setXrActivityVisible(context: Context, visible: Boolean) { 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/ui/AddAppDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt index bee26dd0dc..5e63d7b0f2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt @@ -23,6 +23,8 @@ import androidx.compose.foundation.LocalIndication import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.hoverable import androidx.compose.foundation.interaction.MutableInteractionSource @@ -493,7 +495,7 @@ private fun IconSuggestions(repo: String, selected: String?, onPick: (String) -> if (list != null && list.isEmpty()) return Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.height(44.dp)) { Small(stringResource(if (list == null) R.string.add_app_icon_searching else R.string.add_app_icon_suggestions)) - if (list != null) Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) { + if (list != null) Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState()).selectableGroup()) { list.forEachIndexed { i, url -> Rise(i) { SuggestedIcon(url, url == selected) { onPick(url) } } } } } @@ -510,7 +512,7 @@ private fun SuggestedIcon(url: String, selected: Boolean, onClick: () -> Unit) { contentAlignment = Alignment.Center, modifier = Modifier.size(44.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(colors.surface) .glideBorder(hot, Shape12, pal.signal, pal.line2) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick) + .hoverable(src).selectable(selected = selected, role = androidx.compose.ui.semantics.Role.RadioButton, interactionSource = src, indication = LocalIndication.current, onClick = onClick) .controllerConfirm(onClick = onClick), ) { AsyncImage(model = ImageRequest.Builder(LocalContext.current).data(url).crossfade(true).build(), contentDescription = stringResource(R.string.add_app_icon), contentScale = ContentScale.Fit, modifier = Modifier.size(34.dp)) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt index e3de1f325e..0e99b6e714 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt @@ -1323,7 +1323,7 @@ internal fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = fa modifier = Modifier.size(44.dp).clip(RoundedCornerShape(12.dp)) .background(if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent) .glideBorder(hot, RoundedCornerShape(12.dp), pal.signal, pal.line2) - .hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick), ) { if (busy) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp)) @@ -1342,7 +1342,7 @@ private fun SmallButton(text: String, enabled: Boolean = true, accent: Boolean = modifier = modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(10.dp)) .background(if (hot) pal.signal else colors.surfaceVariant) .glideBorder(hot, RoundedCornerShape(10.dp), colors.onBackground, pal.line2, restWidth = 2.dp) - .hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = 14.dp, vertical = 8.dp), ) { @@ -1422,7 +1422,7 @@ private fun ChoiceLine( modifier = Modifier.padding(end = 6.dp).size(44.dp).clip(ROW_SHAPE) .background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent) .glideBorder(delHot, ROW_SHAPE, colors.error) - .hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete) + .hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, onClick = onDelete) .controllerConfirm(onClick = onDelete), ) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt index bfdde089a6..2a22c0a155 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt @@ -15,6 +15,7 @@ import androidx.compose.ui.focus.focusProperties import androidx.compose.ui.focus.focusRequester import androidx.compose.foundation.border import androidx.compose.foundation.clickable +import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -105,7 +106,7 @@ fun DriverPage( .glideBorder(refreshHot, RoundedCornerShape(10.dp), pal.signal, pal.line) .focusRequester(refreshFocus) .hoverable(refreshSrc) - .clickable(interactionSource = refreshSrc, indication = null, enabled = !checking, onClick = onRefresh), + .clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = refreshSrc, indication = null, enabled = !checking, onClick = onRefresh), ) { if (checking) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp)) else Icon(Icons.Outlined.Refresh, contentDescription = stringResource(R.string.comp_check_drivers), tint = colors.onBackground, modifier = Modifier.size(20.dp)) @@ -185,7 +186,7 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).then(modifier).focusRequester(mainFocus) .then(if (row.removable) Modifier.focusProperties { right = delFocus } else Modifier) - .hoverable(src).clickable(interactionSource = src, indication = null, onClick = onSelect) + .hoverable(src).selectable(selected = selected, role = androidx.compose.ui.semantics.Role.RadioButton, interactionSource = src, indication = null, onClick = onSelect) .padding(horizontal = 11.dp, vertical = 8.dp), ) { Box( @@ -218,7 +219,7 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit .glideBorder(delHot, RoundedCornerShape(10.dp), colors.error) .focusRequester(delFocus) .focusProperties { left = mainFocus } - .hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete), + .hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, onClick = onDelete), ) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, row.name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) } } } @@ -235,7 +236,7 @@ internal fun FocusText(text: String, color: Color, modifier: Modifier = Modifier modifier = modifier.clip(shape) .background(if (hot) color.copy(alpha = 0.14f) else Color.Transparent) .glideBorder(hot, shape, color) - .hoverable(src).clickable(interactionSource = src, indication = null, onClick = onClick) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, onClick = onClick) .padding(horizontal = 12.dp, vertical = 8.dp), ) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndArt.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndArt.kt index 85386ca935..eef6fd19ca 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndArt.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndArt.kt @@ -131,7 +131,7 @@ private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableIntera .background(colors.surface) .glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp) .alpha(if (t.dim && !hot) 0.55f else 1f) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = t.onClick), + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = t.onClick), ) { Box(modifier = Modifier.fillMaxWidth().shine(hot)) { Art(t.art, t.iconRes, t.title, Modifier.fillMaxWidth(), wide, t.iconBitmap) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt index f86062e241..dcb5eece6d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt @@ -559,7 +559,7 @@ private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Uni .clip(Shape12) .background(if (selected) pal.signal.copy(alpha = 0.14f) else if (hovered) Color.White.copy(alpha = 0.05f) else Color.Transparent) .glideBorder(focused, Shape12, pal.signal) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onSelect) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onSelect) .controllerConfirm(onClick = onLaunch) .padding(horizontal = 10.dp, vertical = 6.dp), ) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index c5a0c6866e..7136ac7f07 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt @@ -22,6 +22,8 @@ import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.hoverable +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsFocusedAsState import androidx.compose.foundation.interaction.collectIsHoveredAsState @@ -119,7 +121,7 @@ internal fun SideRail( Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp), - modifier = Modifier.fillMaxWidth(), + modifier = Modifier.fillMaxWidth().selectableGroup(), ) { val place: (String) -> Modifier = { key -> Modifier.onGloballyPositioned { @@ -192,7 +194,7 @@ private fun RailItem( .background(fill) .glideBorder(focused, Shape14, pal.signal) .hoverable(src) - .clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick) + .selectable(selected = current, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick) .then(if (iconOnly) Modifier.semantics { contentDescription = label } else Modifier), ) { if (iconOnly) Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(22.dp)) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/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/LiftSheet.kt b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt index 01240610dd..c428b8b97d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt @@ -18,6 +18,8 @@ import androidx.compose.foundation.focusGroup import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.detectVerticalDragGestures import androidx.compose.foundation.hoverable +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsHoveredAsState import androidx.compose.foundation.layout.Arrangement @@ -715,7 +717,7 @@ internal fun SheetChips( horizontalArrangement = Arrangement.spacedBy(ChipGap), modifier = (if (equal) Modifier.fillMaxWidth() else Modifier) .focusProperties { enter = { chips.getOrNull(selected) ?: FocusRequester.Default } } - .focusGroup(), + .focusGroup().selectableGroup(), ) { labels.forEachIndexed { i, label -> val m = (if (equal) Modifier.weight(1f) else Modifier.widthIn(min = least)) @@ -743,7 +745,7 @@ private fun SheetChip(label: String, on: Boolean, modifier: Modifier, onClick: ( .background(if (under) Color.Transparent else colors.surfaceVariant.copy(alpha = 0.5f)) .shownBar(on, pal.signal) .glideBorder(hot, shape, pal.signal, if (under) Color.Transparent else pal.line) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick) + .hoverable(src).selectable(selected = on, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick) .controllerConfirm(onClick = onClick) .padding(horizontal = 14.dp, vertical = 8.dp), ) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index cb7ec92516..778673e92d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -88,6 +88,7 @@ class ModeSettings( val mangoapp: Boolean = true, val steamController: String? = null, val unfoldedControls: Boolean? = null, + val unfoldedControlsWithController: Boolean = false, val runSteamAtStartup: Boolean = false, val bootMovie: String? = null, val bootMovieSound: Boolean = true, @@ -140,6 +141,7 @@ class ModeSettingsActions( val onReturnAfterGame: (Boolean) -> Unit = {}, val onSteamController: (String) -> Unit = {}, val onUnfoldedControls: (Boolean) -> Unit = {}, + val onUnfoldedControlsWithController: (Boolean) -> Unit = {}, val onRunSteamAtStartup: (Boolean) -> Unit = {}, val onBootMovie: (String) -> Unit = {}, val onBootMovieSound: (Boolean) -> Unit = {}, @@ -290,6 +292,11 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: stringResource(R.string.unfolded_controls_hint), s.unfoldedControls, onChange = a.onUnfoldedControls, ) + if (steam && s.unfoldedControls == true) ToggleRow( + host, "unfolded-controls-with-controller", stringResource(R.string.unfolded_controls_with_controller), + stringResource(R.string.unfolded_controls_with_controller_hint), + s.unfoldedControlsWithController, onChange = a.onUnfoldedControlsWithController, + ) if (steam) ChoiceRow( host, "back-actions", stringResource(R.string.mode_back), stringResource(SessionPrefs.backActionsOrder(s.backActionsInverted)), listOf( diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt b/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt index 0567319f30..0fc5762777 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt @@ -234,7 +234,7 @@ private fun HeaderButton(text: String, onClick: () -> Unit) { modifier = Modifier.fillMaxHeight() .background(Color.White.copy(alpha = 0.08f), RoundedCornerShape(7.dp)) .glideBorder(focused, RoundedCornerShape(7.dp), pal.signal, Color.White.copy(alpha = 0.14f)) - .clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick) + .clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onClick) .padding(horizontal = 12.dp), ) { Text(text, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = Color.White) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 962cdef820..58b4c11eea 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -278,6 +278,8 @@ class DrawerActions( val onPipAutoEnter: (Boolean) -> Unit = {}, val unfoldedControls: Boolean? = null, val onUnfoldedControls: (Boolean) -> Unit = {}, + val unfoldedControlsWithController: Boolean = false, + val onUnfoldedControlsWithController: (Boolean) -> Unit = {}, val onShareLogs: () -> Unit, val onStop: () -> Unit, val onStopFrom: ((androidx.compose.ui.geometry.Rect?) -> Unit)? = null, @@ -575,6 +577,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls), stringResource(R.string.unfolded_controls_hint), a.unfoldedControls, chipModifier = focus.track(page, "unfolded-controls"), onChange = a.onUnfoldedControls) + if (a.steam && a.unfoldedControls == true) ToggleRow(host, "unfolded-controls-with-controller", + stringResource(R.string.unfolded_controls_with_controller), + stringResource(R.string.unfolded_controls_with_controller_hint), a.unfoldedControlsWithController, + chipModifier = focus.track(page, "unfolded-controls-with-controller"), + onChange = a.onUnfoldedControlsWithController) } SettingsGroup(stringResource(R.string.drawer_latency)) { ToggleRow(host, "low-latency-controller", stringResource(R.string.drawer_low_latency_controller), @@ -754,7 +761,7 @@ private fun DrawerActionButton(text: String, icon: androidx.compose.ui.graphics. modifier = modifier.fillMaxWidth().heightIn(min = 52.dp).clip(shape) .background(if (hot) pal.signal.copy(alpha = 0.16f) else colors.surfaceVariant) .glideBorder(hot, shape, pal.signal) - .hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, onClick = onClick) + .hoverable(source).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = source, indication = LocalIndication.current, onClick = onClick) .controllerConfirm(onClick = onClick).padding(horizontal = 16.dp, vertical = 10.dp), ) { Icon(icon, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(22.dp)) @@ -791,7 +798,7 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = modifier.heightIn(min = 44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop") .clip(shape).background(fill).glideBorder(hot, shape, colors.error.copy(alpha = 0.9f), colors.error.copy(alpha = 0.55f)) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onClick) .controllerConfirm(onClick = onClick) .padding(start = 12.dp, end = 14.dp), ) { @@ -817,7 +824,7 @@ private fun SteamActionPill( .clip(shape).background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent) .glideBorder(hot, shape, pal.signal, pal.line) .hoverable(interactionSource) - .clickable(interactionSource = interactionSource, indication = LocalIndication.current, onClick = onClick) + .clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = interactionSource, indication = LocalIndication.current, onClick = onClick) .controllerConfirm(onClick = onConfirm ?: onClick), ) { Icon(icon, contentDescription = null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(20.dp)) @@ -836,7 +843,7 @@ private fun DrawerBumper(label: String, description: String, modifier: Modifier contentAlignment = Alignment.Center, modifier = modifier.size(44.dp).clip(ring) .glideBorder(hot, ring, pal.signal) - .hoverable(src).clickable(interactionSource = src, indication = null, onClick = onClick) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, onClick = onClick) .controllerConfirm(onClick = onClick) .semantics { contentDescription = description }, ) { @@ -857,7 +864,7 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List(340, easing = FastOutSlowInEasing) androidx.compose.foundation.layout.BoxWithConstraints( contentAlignment = Alignment.Center, - modifier = modifier.height(if (compact) 44.dp else 64.dp).clipToBounds(), + modifier = modifier.height(if (compact) 44.dp else 64.dp).clipToBounds().selectableGroup(), ) { val tab = if (compact) 36f else 44f val spacing = ((maxWidth.value - tab) / ((count - 1) * (1f + DRAWER_TAB_LEAN_DP / DRAWER_TAB_SPACING_DP))).coerceIn(24f, DRAWER_TAB_SPACING_DP) @@ -890,7 +897,7 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List val on = i == selected @@ -197,7 +199,7 @@ internal fun TabStrip( .clip(tabShape) .background(if (on) pal.signal else if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent) .glideBorder(hot, tabShape, if (on) colors.onBackground else pal.signal) - .hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Tab, onClick = pick) + .hoverable(src).selectable(selected = on, interactionSource = src, indication = null, role = Role.Tab, onClick = pick) .controllerConfirm(onClick = pick) .padding(horizontal = tabPadding, vertical = if (compact) 6.dp else 12.dp), ) @@ -367,7 +369,7 @@ fun MenuItem( .clip(RoundedCornerShape(8.dp)) .background(if (hot && enabled) Color.White.copy(alpha = 0.07f) else Color.Transparent) .alpha(if (enabled) 1f else 0.4f) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = 10.dp, vertical = 9.dp), ) { @@ -400,7 +402,7 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo .background(colors.surfaceVariant) .glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, if (open) pal.signal else pal.line2) .alpha(if (enabled) 1f else 0.5f) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = 12.dp, vertical = 8.dp), ) { @@ -791,7 +793,7 @@ fun SegmentedTabs(options: List>, selected: T?, modifier: Mo .graphicsLayer { alpha = shown } .clip(pillShape).background(pal.signal), ) - Row { + Row(Modifier.selectableGroup()) { options.forEachIndexed { i, (value, label) -> val src = remember { MutableInteractionSource() } val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value @@ -810,9 +812,8 @@ fun SegmentedTabs(options: List>, selected: T?, modifier: Mo modifier = tabModifier(value).width(segment).fillMaxHeight() .clip(pillShape) .glideBorder(hot, pillShape, if (chosen) pal.onSignal else pal.signal) - .semantics { role = Role.Tab; this.selected = chosen } .hoverable(src) - .clickable(interactionSource = src, indication = LocalIndication.current, onClick = pick) + .selectable(selected = chosen, role = Role.Tab, interactionSource = src, indication = LocalIndication.current, onClick = pick) .controllerConfirm(onClick = pick), ) { Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = ink, maxLines = 1, softWrap = false) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt index 4f71f68b38..1492362f12 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt @@ -370,7 +370,7 @@ internal fun DrawerAchievementsRow(progress: Pair?, modifier: Modifier modifier = modifier.fillMaxWidth().height(44.dp).clip(shape) .background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface) .glideBorder(hot, shape, pal.signal, pal.line) - .clickable(interactionSource = interaction, indication = LocalIndication.current, onClick = onClick) + .clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = interaction, indication = LocalIndication.current, onClick = onClick) .controllerConfirm(onClick = onClick) .padding(horizontal = 12.dp), ) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index 182f3a1d52..175cbecd85 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -60,6 +60,8 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.focusGroup import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.hoverable +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Arrangement @@ -1150,7 +1152,7 @@ private fun HeaderTabs(labels: List, selected: Int, onSelect: (Int) -> U val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val shape = RoundedCornerShape(8.dp) - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.selectableGroup()) { labels.forEachIndexed { i, label -> val src = remember { MutableInteractionSource() } val hot = rememberHot(src) @@ -1159,7 +1161,7 @@ private fun HeaderTabs(labels: List, selected: Int, onSelect: (Int) -> U label, fontSize = 15.sp, fontWeight = FontWeight.Bold, maxLines = 1, color = if (i == selected || hot) colors.onBackground else colors.onSurfaceVariant.copy(alpha = 0.7f), modifier = Modifier.clip(shape).glideBorder(hot, shape, pal.signal) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = pick) + .hoverable(src).selectable(selected = i == selected, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = pick) .controllerConfirm(onClick = pick) .padding(horizontal = 4.dp, vertical = 6.dp), ) @@ -1363,7 +1365,7 @@ private fun GameListRow( modifier = Modifier.fillMaxWidth().heightIn(min = 64.dp).then(navigation).paneItem("card:${item.key}") .then(if (first) Modifier.firstTile() else Modifier) .clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open) + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open) .padding(horizontal = 10.dp, vertical = 8.dp), ) { CardArt(item, Modifier.width(96.dp).height(54.dp).clip(RoundedCornerShape(8.dp))) @@ -1481,7 +1483,7 @@ private fun GameCard( } .then(navigation).paneItem("card:${item.key}").then(if (first) Modifier.firstTile() else Modifier).graphicsLayer { scaleX = scale; scaleY = scale } .clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open), + .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open), ) { CardFace(item, download, hot, capsule) { CardMarker(item, installed, download, compact = capsule) } } diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index b29ced8a7f..ffa9537d9c 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -1159,6 +1159,8 @@ Otomatik olarak PiP moduna geç Açılmış ekrandaki kontroller Cihaz açıkken oyun, Steam Deck dokunmatik yüzeylerinin ve arka tutamaklarının üstünde durur. Katlıyken oyun tam ekran olur. + Kumanda bağlıyken de göster + Telefonu tutan kumandalar için, kumanda bağlıyken de açılmış ekrandaki kontrolleri gösterir. Askıya alındı Pencere içinde pencere, oturum hazır olduğunda kullanılabilir. Android ayarlarında DroidDeck için pencere içinde pencereye izin verin. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e3771171e8..5ca139d367 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1210,6 +1210,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. 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/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/tools/desktop-kde/README.md b/tools/desktop-kde/README.md index ced96147e1..b76457f60f 100644 --- a/tools/desktop-kde/README.md +++ b/tools/desktop-kde/README.md @@ -22,9 +22,11 @@ through `kwin_wayland_wrapper`. KWin composites in software (QPainter) - the Adr DRM device - so games and emulators from the menu go through `droiddeck-gpu`, and Steam goes back to the app as a Steam session. -`build-kwin.sh` builds KWin 6.7.5's Wayland executable and library on a native ARM64 runner, using a disposable -Arch Linux ARM chroot with every build package signature-checked. The KDE source tarball is pinned -by SHA-256 (the same digest in Arch's KWin PKGBUILD); `patches/0001-respect-nested-desktop-scale.patch` +`kwin.env` pins the KWin version shared by the build and packaging jobs. `build-kwin.sh` builds that version's +Wayland executable and library on a native ARM64 runner, using a disposable +Arch Linux ARM chroot with every build package signature-checked. It matches the current KWin package +in Arch Linux ARM even when that repository trails KDE's latest release. The source tarball is pinned +by SHA-256 from KDE's official source inventory; `patches/0001-respect-nested-desktop-scale.patch` lets Display Settings control the inner desktop scale independently of the outer window size. It keeps layer sizes, pointer/touch coordinates and the cursor in the same physical pixels. The behavior is enabled only with `DROIDDECK_NESTED_SCALE`, which the desktop script supplies. @@ -32,7 +34,7 @@ The behavior is enabled only with `DROIDDECK_NESTED_SCALE`, which the desktop sc The desktop workflow replaces the same-version `kwin_wayland` executable and `libkwin.so`; the rest comes from the signature-checked Arch packages. `desktop-kde.kwin.txt` records the source, patch, executable, library and build package hashes. Corresponding source is -https://download.kde.org/stable/plasma/6.7.5/kwin-6.7.5.tar.xz plus the patch in this repository. +https://download.kde.org/stable/plasma/6.8.0/kwin-6.8.0.tar.xz plus the patch in this repository. The inventories use `.gzip` rather than `.gz`: Android's asset packer expands `.gz` and strips its suffix. The shared local/CI runtime payload check verifies the exact APK names and bytes. diff --git a/tools/desktop-kde/build-kwin.sh b/tools/desktop-kde/build-kwin.sh index ae6ac49430..c740d484ab 100644 --- a/tools/desktop-kde/build-kwin.sh +++ b/tools/desktop-kde/build-kwin.sh @@ -3,8 +3,9 @@ set -euo pipefail out=$(realpath -m "${1:?out dir}") here=$(cd "$(dirname "$0")" && pwd) [ "$(uname -m)" = aarch64 ] || { echo 'KWin needs a native aarch64 runner' >&2; exit 1; } -version=6.7.5 -source_sha=6baa910b732d93c48c90f9c1cc685cc93d0b8de0cdf138c24192c045bc3a48e2 +source "$here/kwin.env" +version=$DESKTOP_KWIN_VERSION +source_sha=4bfaf31e29a8f9fdf231dc3bbb9b09b0ce07cae9fee7a01cfc86425ece796258 mirror=https://fl.us.mirror.archlinuxarm.org/aarch64 builder=68B3537F39A313B3E574D06777193F152BDBE6A6 work=$(mktemp -d) @@ -18,7 +19,11 @@ for repo in core extra alarm; do done touch "$work/runtime.txt" python3 "$here/closure.py" "$work/db" "$work/runtime.txt" "$here/kwin-build-seeds.txt" > "$work/packages.txt" -grep -Eq '^extra/kwin-6\.7\.5-[0-9]+-aarch64\.pkg\.tar\.' "$work/packages.txt" +kwin_package=$(awk '$1 ~ /^extra\/kwin-.*-aarch64\.pkg\.tar\./ {print $1}' "$work/packages.txt") +case $kwin_package in + "extra/kwin-$version"-[0-9]*-aarch64.pkg.tar.*) ;; + *) echo "KWin package $kwin_package does not match source KWin $version" >&2; exit 1 ;; +esac export work mirror builder here download() { local entry=$1 sum=$2 file=${1#*/} diff --git a/tools/desktop-kde/build.sh b/tools/desktop-kde/build.sh index 80bd41e11a..b434e81bc5 100755 --- a/tools/desktop-kde/build.sh +++ b/tools/desktop-kde/build.sh @@ -2,6 +2,7 @@ set -euo pipefail out=${1:?out dir} here=$(cd "$(dirname "$0")" && pwd) +source "$here/kwin.env" mirror=${ALARM_MIRROR:-https://fl.us.mirror.archlinuxarm.org/aarch64} case $mirror in https://*) ;; *) echo "ALARM_MIRROR must be https" >&2; exit 1 ;; esac builder=68B3537F39A313B3E574D06777193F152BDBE6A6 @@ -36,8 +37,13 @@ done < "$work/pkglist.txt" cp -a "$here/overlay/." "$work/root/" if [ -n "${KDE_KWIN_OVERRIDE:-}" ]; then + kwin_package=$(awk '$1 ~ /^extra\/kwin-.*-aarch64\.pkg\.tar\./ {print $1}' "$work/pkglist.txt") + case $kwin_package in + "extra/kwin-$DESKTOP_KWIN_VERSION"-[0-9]*-aarch64.pkg.tar.*) ;; + *) echo "KWin package $kwin_package does not match the built KWin $DESKTOP_KWIN_VERSION" >&2; exit 1 ;; + esac install -m 755 "$KDE_KWIN_OVERRIDE/kwin_wayland" "$work/root/usr/bin/kwin_wayland" - install -m 755 "$KDE_KWIN_OVERRIDE/libkwin.so.6.7.5" "$work/root/usr/lib/libkwin.so.6.7.5" + install -m 755 "$KDE_KWIN_OVERRIDE/libkwin.so.$DESKTOP_KWIN_VERSION" "$work/root/usr/lib/libkwin.so.$DESKTOP_KWIN_VERSION" fi if [ -d "$work/root/usr/share/locale" ]; then diff --git a/tools/desktop-kde/kwin.env b/tools/desktop-kde/kwin.env new file mode 100644 index 0000000000..d6ef0cee96 --- /dev/null +++ b/tools/desktop-kde/kwin.env @@ -0,0 +1 @@ +DESKTOP_KWIN_VERSION=6.8.0 diff --git a/tools/desktop-kde/overlay/usr/share/licenses/droiddeck-desktop/NOTICE b/tools/desktop-kde/overlay/usr/share/licenses/droiddeck-desktop/NOTICE index 23bc15cc14..a806a082e6 100644 --- a/tools/desktop-kde/overlay/usr/share/licenses/droiddeck-desktop/NOTICE +++ b/tools/desktop-kde/overlay/usr/share/licenses/droiddeck-desktop/NOTICE @@ -8,8 +8,8 @@ Third-party files in DroidDeck's KDE desktop package (tools/desktop-kde/overlay) - steam.svg: Papirus icon theme (https://github.com/PapirusDevelopmentTeam/papirus-icon-theme), GPL-3.0. -- kwin_wayland: KWin 6.7.5, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch. - Corresponding source: https://download.kde.org/stable/plasma/6.7.5/kwin-6.7.5.tar.xz and +- kwin_wayland: KWin 6.8.0, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch. + Corresponding source: https://download.kde.org/stable/plasma/6.8.0/kwin-6.8.0.tar.xz and https://github.com/Droid-Deck/DroidDeck/tree/fix/kde-desktop-followups/tools/desktop-kde/patches (the source and patch hashes are recorded in desktop-kde.kwin.txt beside the package). diff --git a/tools/desktop-kde/patches/0001-respect-nested-desktop-scale.patch b/tools/desktop-kde/patches/0001-respect-nested-desktop-scale.patch index 7c8767ff81..8ad3a5238a 100644 --- a/tools/desktop-kde/patches/0001-respect-nested-desktop-scale.patch +++ b/tools/desktop-kde/patches/0001-respect-nested-desktop-scale.patch @@ -1,78 +1,27 @@ ---- a/src/backends/wayland/wayland_output.cpp -+++ b/src/backends/wayland/wayland_output.cpp -@@ -294,6 +294,11 @@ - } - } - -+qreal WaylandOutput::presentationScale() const -+{ -+ return qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE") ? m_pendingScale : scale(); -+} -+ - bool WaylandOutput::present(const QList &layersToUpdate, const std::shared_ptr &frame) - { - auto cursorLayers = layersToUpdate | std::views::filter([](OutputLayer *layer) { -@@ -312,7 +317,7 @@ - m_surface->attachBuffer(buffer); - m_mapped = true; - } -- m_viewport->setDestination(QSize(std::round(modeSize().width() / scale()), std::round(modeSize().height() / scale()))); -+ m_viewport->setDestination(QSize(std::round(modeSize().width() / presentationScale()), std::round(modeSize().height() / presentationScale()))); - m_surface->setScale(1); - // commit the subsurfaces before the main surface - for (OutputLayer *layer : layersToUpdate) { -@@ -375,9 +380,11 @@ - next.enabled = props->enabled.value_or(m_state.enabled); - next.transform = props->transform.value_or(m_state.transform); - next.position = props->pos.value_or(m_state.position); -- // intentionally ignored, as it would get overwritten -- // with the fractional scale protocol anyways -- // next.scale = props->scale.value_or(m_state.scale); -+ -+ if (qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) { -+ next.scale = props->scale.value_or(m_state.scale); -+ next.scaleSetting = props->scaleSetting.value_or(m_state.scaleSetting); -+ } - next.desiredMode = props->desiredMode.value_or(m_state.desiredMode); - next.uuid = props->uuid.value_or(m_state.uuid); - next.replicationSource = props->replicationSource.value_or(m_state.replicationSource); -@@ -466,7 +473,9 @@ - State next = m_state; - next.modes = {mode}; - next.currentMode = mode; -- next.scale = m_pendingScale; -+ if (!qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) { -+ next.scale = m_pendingScale; -+ } - setState(next); - - Q_EMIT m_backend->outputsQueried(); ---- a/src/backends/wayland/wayland_output.h -+++ b/src/backends/wayland/wayland_output.h -@@ -93,6 +93,8 @@ - - void init(const QSize &pixelSize, qreal scale, bool fullscreen); - -+ -+ qreal presentationScale() const; - bool isReady() const; - KWayland::Client::Surface *surface() const; - WaylandCursor *cursor() const; +diff --git a/src/backends/wayland/wayland_backend.cpp b/src/backends/wayland/wayland_backend.cpp +index f43f03d..211ef09 100644 --- a/src/backends/wayland/wayland_backend.cpp +++ b/src/backends/wayland/wayland_backend.cpp -@@ -107,8 +107,9 @@ +@@ -106,16 +106,8 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::Pointer *pointer, Wayla WaylandOutput *output = m_seat->backend()->findOutput(m_pointer->enteredSurface()); Q_ASSERT(output); const auto subsurface = m_seat->backend()->findSubSurface(m_pointer->enteredSurface()); -- const QPointF absolutePos = output->position() + relativeToSurface -- + (subsurface ? subsurface->position() : QPoint()); -+ const QPointF absolutePos = output->position() -+ + (relativeToSurface + (subsurface ? subsurface->position() : QPoint())) -+ * output->presentationScale() / output->scale(); +- // A position in the host window is in the coordinates the panel is driven in, while +- // the compositor works in the picture as the user sees it. On a rotated display those +- // are not the same, so the position has to be turned back. +- const QPointF inPanel = relativeToSurface + (subsurface ? subsurface->position() : QPoint()); +- // Exactly the size the surface is given in WaylandOutput::present(), rounding and all - +- // turning a position needs the bounds it was expressed in, and being off by the +- // rounding here shifts the pointer by a little more the further it travels. +- const QSizeF panelSize = QSize(std::round(output->modeSize().width() / output->scale()), +- std::round(output->modeSize().height() / output->scale())); +- const QPointF absolutePos = output->position() + output->transform().inverted().map(inPanel, panelSize); ++ const QPointF hostPosition = relativeToSurface + (subsurface ? subsurface->position() : QPoint()); ++ const QPointF absolutePos = output->mapToOutput(hostPosition); Q_EMIT pointerMotionAbsolute(absolutePos, std::chrono::milliseconds(time), this); }); connect(pointer, &Pointer::buttonStateChanged, this, [this](quint32 serial, quint32 time, quint32 button, Pointer::ButtonState nativeState) { -@@ -182,7 +183,11 @@ +@@ -189,7 +181,11 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::RelativePointer *relati , m_relativePointer(relativePointer) { connect(relativePointer, &RelativePointer::relativeMotion, this, [this](const QSizeF &delta, const QSizeF &deltaNonAccelerated, quint64 timestamp) { @@ -84,16 +33,17 @@ + Q_EMIT pointerMotion(sizeToPoint(delta) * factor, sizeToPoint(deltaNonAccelerated) * factor, std::chrono::microseconds(timestamp), this); }); } - -@@ -199,13 +204,19 @@ + +@@ -206,13 +202,21 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::Touch *touch, WaylandSe connect(touch, &Touch::sequenceStarted, this, [this](TouchPoint *tp) { auto o = m_seat->backend()->findOutput(tp->surface()); Q_ASSERT(o); - const QPointF position = o->position() + tp->position(); + const auto subsurface = m_seat->backend()->findSubSurface(tp->surface()); -+ const QPointF position = o->position() -+ + (tp->position() + (subsurface ? subsurface->position() : QPoint())) -+ * o->presentationScale() / o->scale(); ++ const QPointF hostPosition = tp->position() + (subsurface ? subsurface->position() : QPoint()); ++ const QPointF position = qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE") ++ ? o->mapToOutput(hostPosition) ++ : o->position() + tp->position(); Q_EMIT touchDown(tp->id(), position, std::chrono::milliseconds(tp->time()), this); }); connect(touch, &Touch::pointAdded, this, [this](TouchPoint *tp) { @@ -101,27 +51,46 @@ Q_ASSERT(o); - const QPointF position = o->position() + tp->position(); + const auto subsurface = m_seat->backend()->findSubSurface(tp->surface()); -+ const QPointF position = o->position() -+ + (tp->position() + (subsurface ? subsurface->position() : QPoint())) -+ * o->presentationScale() / o->scale(); ++ const QPointF hostPosition = tp->position() + (subsurface ? subsurface->position() : QPoint()); ++ const QPointF position = qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE") ++ ? o->mapToOutput(hostPosition) ++ : o->position() + tp->position(); Q_EMIT touchDown(tp->id(), position, std::chrono::milliseconds(tp->time()), this); }); connect(touch, &Touch::pointRemoved, this, [this](TouchPoint *tp) { -@@ -214,7 +225,10 @@ +@@ -221,7 +225,11 @@ WaylandInputDevice::WaylandInputDevice(KWayland::Client::Touch *touch, WaylandSe connect(touch, &Touch::pointMoved, this, [this](TouchPoint *tp) { auto o = m_seat->backend()->findOutput(tp->surface()); Q_ASSERT(o); - const QPointF position = o->position() + tp->position(); + const auto subsurface = m_seat->backend()->findSubSurface(tp->surface()); -+ const QPointF position = o->position() -+ + (tp->position() + (subsurface ? subsurface->position() : QPoint())) -+ * o->presentationScale() / o->scale(); ++ const QPointF hostPosition = tp->position() + (subsurface ? subsurface->position() : QPoint()); ++ const QPointF position = qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE") ++ ? o->mapToOutput(hostPosition) ++ : o->position() + tp->position(); Q_EMIT touchMotion(tp->id(), position, std::chrono::milliseconds(tp->time()), this); }); } +diff --git a/src/backends/wayland/wayland_egl_backend.cpp b/src/backends/wayland/wayland_egl_backend.cpp +index 0c03222..c587db5 100644 +--- a/src/backends/wayland/wayland_egl_backend.cpp ++++ b/src/backends/wayland/wayland_egl_backend.cpp +@@ -232,7 +232,9 @@ bool WaylandEglCursorLayer::endFrame(const Region &renderedDeviceRegion, const R + wl_buffer *buffer = m_backend->backend()->importBuffer(m_buffer->buffer()); + Q_ASSERT(buffer); + +- static_cast(m_output.get())->cursor()->update(buffer, m_buffer->buffer()->size() / m_output->scale(), (hotspot() / m_output->scale()).toPoint()); ++ auto output = static_cast(m_output.get()); ++ output->cursor()->update(buffer, m_buffer->buffer()->size() / output->presentationScale(), ++ (hotspot() / output->presentationScale()).toPoint()); + + EGLNativeFence releaseFence{m_backend->eglDisplayObject()}; + m_swapchain->release(m_buffer, releaseFence.takeFileDescriptor()); +diff --git a/src/backends/wayland/wayland_layer.cpp b/src/backends/wayland/wayland_layer.cpp +index 311be7f..f91a3fb 100644 --- a/src/backends/wayland/wayland_layer.cpp +++ b/src/backends/wayland/wayland_layer.cpp -@@ -95,7 +95,7 @@ +@@ -95,7 +95,7 @@ void WaylandLayer::commit(PresentationMode presentationMode) // this is a bit annoying, we need a new Wayland protocol // to do this properly with fractional scaling. Until we // have that, it may cause blurriness in some cases! @@ -130,29 +99,74 @@ if (m_viewport) { m_viewport->setSource(sourceRect()); m_viewport->setDestination(logicalTarget.size()); ---- a/src/backends/wayland/wayland_qpainter_backend.cpp -+++ b/src/backends/wayland/wayland_qpainter_backend.cpp -@@ -124,7 +124,9 @@ - wl_buffer *buffer = static_cast(m_output.get())->backend()->importBuffer(m_back->buffer()); - Q_ASSERT(buffer); - -- static_cast(m_output.get())->cursor()->update(buffer, m_back->buffer()->size() / m_output->scale(), hotspot().toPoint()); -+ auto output = static_cast(m_output.get()); -+ output->cursor()->update(buffer, m_back->buffer()->size() / output->presentationScale(), -+ (hotspot() * output->scale() / output->presentationScale()).toPoint()); - m_swapchain->release(m_back); - return true; +diff --git a/src/backends/wayland/wayland_output.cpp b/src/backends/wayland/wayland_output.cpp +index 1543058..a22d974 100644 +--- a/src/backends/wayland/wayland_output.cpp ++++ b/src/backends/wayland/wayland_output.cpp +@@ -314,7 +314,7 @@ std::expected WaylandOutput::present(const QListattachBuffer(buffer); + m_mapped = true; + } +- const Rect rect(QPoint(), QSize(std::round(modeSize().width() / scale()), std::round(modeSize().height() / scale()))); ++ const Rect rect(QPoint(), QSize(std::round(modeSize().width() / presentationScale()), std::round(modeSize().height() / presentationScale()))); + m_xdgShellSurface->setWindowGeometry(rect); + m_viewport->setDestination(rect.size()); + m_surface->setScale(1); +@@ -379,9 +379,10 @@ void WaylandOutput::applyChanges(const OutputConfiguration &config) + next.enabled = props->enabled.value_or(m_state.enabled); + next.transform = props->transform.value_or(m_state.transform); + next.position = props->pos.value_or(m_state.position); +- // intentionally ignored, as it would get overwritten +- // with the fractional scale protocol anyways +- // next.scale = props->scale.value_or(m_state.scale); ++ if (qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) { ++ next.scale = props->scale.value_or(m_state.scale); ++ next.scaleSetting = props->scaleSetting.value_or(m_state.scaleSetting); ++ } + next.desiredMode = props->desiredMode.value_or(m_state.desiredMode); + next.uuid = props->uuid.value_or(m_state.uuid); + next.replicationSource = props->replicationSource.value_or(m_state.replicationSource); +@@ -397,6 +398,19 @@ void WaylandOutput::applyChanges(const OutputConfiguration &config) + setState(next); } ---- a/src/backends/wayland/wayland_egl_backend.cpp -+++ b/src/backends/wayland/wayland_egl_backend.cpp -@@ -202,7 +202,9 @@ - wl_buffer *buffer = m_backend->backend()->importBuffer(m_buffer->buffer()); - Q_ASSERT(buffer); - -- static_cast(m_output.get())->cursor()->update(buffer, m_buffer->buffer()->size() / m_output->scale(), (hotspot() / m_output->scale()).toPoint()); -+ auto output = static_cast(m_output.get()); -+ output->cursor()->update(buffer, m_buffer->buffer()->size() / output->presentationScale(), -+ (hotspot() / output->presentationScale()).toPoint()); - - EGLNativeFence releaseFence{m_backend->eglDisplayObject()}; - m_swapchain->release(m_buffer, releaseFence.takeFileDescriptor()); + ++qreal WaylandOutput::presentationScale() const ++{ ++ return qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE") ? m_pendingScale : scale(); ++} ++ ++QPointF WaylandOutput::mapToOutput(const QPointF &hostPosition) const ++{ ++ const QPointF inPanel = hostPosition * presentationScale() / scale(); ++ const QSizeF panelSize = QSize(std::round(modeSize().width() / scale()), ++ std::round(modeSize().height() / scale())); ++ return position() + transform().inverted().map(inPanel, panelSize); ++} ++ + bool WaylandOutput::isReady() const + { + return m_ready; +@@ -472,7 +486,9 @@ void WaylandOutput::applyConfigure(const QSize &size, quint32 serial) + State next = m_state; + next.modes = {mode}; + next.currentMode = mode; +- next.scale = m_pendingScale; ++ if (!qEnvironmentVariableIsSet("DROIDDECK_NESTED_SCALE")) { ++ next.scale = m_pendingScale; ++ } + setState(next); + + Q_EMIT m_backend->outputsQueried(); +diff --git a/src/backends/wayland/wayland_output.h b/src/backends/wayland/wayland_output.h +index dab061b..c019577 100644 +--- a/src/backends/wayland/wayland_output.h ++++ b/src/backends/wayland/wayland_output.h +@@ -92,6 +92,8 @@ public: + + void init(const QSize &pixelSize, qreal scale, bool fullscreen); + ++ qreal presentationScale() const; ++ QPointF mapToOutput(const QPointF &hostPosition) const; + bool isReady() const; + KWayland::Client::Surface *surface() const; + WaylandCursor *cursor() const; diff --git a/tools/device-smoke.sh b/tools/device-smoke.sh new file mode 100755 index 0000000000..bec8fed81b --- /dev/null +++ b/tools/device-smoke.sh @@ -0,0 +1,287 @@ +#!/usr/bin/env bash +# Smoke test of a DroidDeck build on a real device, over plain adb (no python, no root). +# +# What it does, in order, and restores afterwards: +# 1. prints the device (model, Android, kernel, page size, SoC); +# 2. installs --apk when given and launches the app; +# 3. checks that the app starts and that nothing in the crash buffer belongs to it; +# 4. changes the display density and the window size and checks the app keeps its process +# (and does not recreate the activity that is on top); +# 5. on a foldable cycles the device state (half-opened, and with --closed also closed) through +# `cmd device_state`, then puts the original state back; +# 6. reads the newest session folder of a debug build: first frame, last frame rate, the +# memory page size and the last process exits. +# +# Usage: tools/device-smoke.sh [--serial SERIAL] [--apk FILE] [--pkg PACKAGE] +# [--no-density] [--no-size] [--no-fold] [--closed] +# Exit status: 0 when no check failed, 1 when one did, 2 for a usage or device problem. +# +# Not a replacement for tools/droiddeck-scenario, which drives a game through the agent bridge; +# this covers what that does not: display changes and foldable states. +set -u +export MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*' + +pkg=com.droiddeck.launcher +serial=${ANDROID_SERIAL:-} +apk= +do_density=1 +do_size=1 +do_fold=1 +do_closed=0 +adb_bin=${ADB:-adb} + +while [ $# -gt 0 ]; do + case $1 in + --serial) [ $# -ge 2 ] || { echo "--serial needs a value" >&2; exit 2; }; serial=$2; shift ;; + --apk) [ $# -ge 2 ] || { echo "--apk needs a value" >&2; exit 2; }; apk=$2; shift ;; + --pkg) [ $# -ge 2 ] || { echo "--pkg needs a value" >&2; exit 2; }; pkg=$2; shift ;; + --no-density) do_density=0 ;; + --no-size) do_size=0 ;; + --no-fold) do_fold=0 ;; + --closed) do_closed=1 ;; + -h|--help) sed -n '2,22p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "unknown option: $1" >&2; exit 2 ;; + esac + shift +done + +adb_cmd=("$adb_bin") +[ -n "$serial" ] && adb_cmd+=(-s "$serial") +A() { + local out rc + out=$("${adb_cmd[@]}" "$@" 2>&1); rc=$? + [ -z "$out" ] || printf '%s\n' "$out" | tr -d '\r' + return $rc +} +sh_() { + local command= arg + for arg in "$@"; do command+="'${arg//\'/\'\\\'\'}' "; done + A shell "$command" +} + +pass=0 fail=0 skip=0 +ok() { echo " PASS $*"; pass=$((pass + 1)); } +bad() { echo " FAIL $*"; fail=$((fail + 1)); } +note() { echo " SKIP $*"; skip=$((skip + 1)); } +head_() { printf '\n== %s\n' "$*"; } + +state=$(A get-state) +if [ "$state" != "device" ]; then + echo "no authorized device (adb get-state: $state)" >&2 + exit 2 +fi + +density_snapshot=$(sh_ wm density) || density_snapshot= +size_snapshot=$(sh_ wm size) || size_snapshot= +orig_density=$(echo "$density_snapshot" | sed -n 's/.*Physical density: \([0-9]*\).*/\1/p' | head -1) +override_density=$(echo "$density_snapshot" | sed -n 's/.*Override density: \([0-9]*\).*/\1/p' | head -1) +override_size=$(echo "$size_snapshot" | sed -n 's/.*Override size: \([0-9]*x[0-9]*\).*/\1/p' | head -1) +ds=$(sh_ cmd device_state state 2>/dev/null) +orig_state=$(echo "$ds" | sed -n "s/.*Committed state: DeviceState{identifier=\([0-9]*\),.*/\1/p" | head -1) +pre_override=$(echo "$ds" | sed -n "s/.*Override state: DeviceState{identifier=\([0-9]*\),.*/\1/p" | head -1) + +density_changed=0 size_changed=0 fold_changed=0 +wm_override() { sed -n "s/.*Override $1: \\([0-9x]*\\).*/\\1/p" | head -1; } +restore_density() { + sh_ wm density "${override_density:-reset}" >/dev/null || return 1 + local current + current=$(sh_ wm density) || return 1 + echo "$current" | grep -q 'Physical density:' || return 1 + [ "$(echo "$current" | wm_override density)" = "$override_density" ] +} +restore_size() { + sh_ wm size "${override_size:-reset}" >/dev/null || return 1 + local current + current=$(sh_ wm size) || return 1 + echo "$current" | grep -q 'Physical size:' || return 1 + [ "$(echo "$current" | wm_override size)" = "$override_size" ] +} +# An override that was already in place (a test lab pins one) is put back; otherwise the request is cancelled. +restore_fold() { if [ -n "$pre_override" ]; then sh_ cmd device_state state "$pre_override" >/dev/null; else sh_ cmd device_state state reset >/dev/null; fi; } + +restore() { + local failed=0 + if [ "$density_changed" = 1 ]; then + if restore_density; then density_changed=0; else bad "could not restore display density"; failed=1; fi + fi + if [ "$size_changed" = 1 ]; then + if restore_size; then size_changed=0; else bad "could not restore window size"; failed=1; fi + fi + if [ "$fold_changed" = 1 ]; then + if restore_fold; then fold_changed=0; else bad "could not restore fold override"; failed=1; fi + fi + return "$failed" +} +finish() { + local status=$? + restore || status=1 + printf '\n%d passed, %d failed, %d skipped\n' "$pass" "$fail" "$skip" + [ "$fail" = 0 ] || status=1 + exit "$status" +} +trap finish EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +top_activity() { + sh_ dumpsys activity activities 2>/dev/null | sed -n 's/.*topResumedActivity=ActivityRecord{[^ ]* u[0-9]* \([^ ]*\) .*/\1/p' | head -1 +} +app_pid() { sh_ pidof "$pkg" | awk '{print $1}'; } +app_crashes() { + local out pat + out=$(sh_ logcat -b crash -d) || return 1 + pat=$(printf '%s' "$pkg" | sed 's/[.[\*^$]/\\&/g') + printf '%s\n' "$out" | grep -c -E "(Process: |Cmdline: |>>> )$pat([ ,<:]|$)" || true +} +relaunches_of() { # $1 = activity class fragment + sh_ logcat -b events -d 2>/dev/null | grep -E 'wm_(relaunch|destroy|create)_activity' | grep -c "$1" +} + +head_ "Device" +echo " model $(sh_ getprop ro.product.manufacturer) $(sh_ getprop ro.product.model)" +echo " android $(sh_ getprop ro.build.version.release) (API $(sh_ getprop ro.build.version.sdk)), One UI $(sh_ getprop ro.build.version.oneui)" +echo " kernel $(sh_ uname -r)" +page=$(sh_ getconf PAGE_SIZE) +echo " page size $page" +echo " soc $(sh_ getprop ro.soc.manufacturer) $(sh_ getprop ro.soc.model) ($(sh_ getprop ro.board.platform))" +echo " gpu $(sh_ cat /sys/class/kgsl/kgsl-3d0/gpu_model 2>/dev/null)" +echo " display $(sh_ wm size | tr '\n' ' ') $(sh_ wm density | tr '\n' ' ')" +[ "$page" = 4096 ] || [ "$page" = 16384 ] && ok "page size is $page" || bad "page size reads '$page'" + +head_ "Install and launch" +sh_ logcat -b crash -c >/dev/null +sh_ logcat -b events -c >/dev/null +if [ -n "$apk" ]; then + r=$(A install -r -t "$apk" | tail -1) + case $r in *Success*) ok "installed $(basename "$apk")" ;; *) bad "install: $r"; exit 1 ;; esac +fi +packages=$(sh_ pm list packages "$pkg") || { echo "could not query installed packages" >&2; exit 2; } +if ! printf '%s\n' "$packages" | grep -Fxq "package:$pkg"; then echo "package $pkg is not installed" >&2; exit 2; fi +if ! launch=$(sh_ am start -n "$pkg/.MainActivity") || printf '%s\n' "$launch" | grep -q '^Error'; then + bad "could not launch $pkg/.MainActivity" +fi +sleep 6 +pid=$(app_pid) +[ -n "$pid" ] && ok "process running (pid $pid)" || bad "the app has no process after launch" +t=$(top_activity) +case $t in + "$pkg"/*|*permissioncontroller*|*GrantPermissions*) ok "top activity: $t" ;; + *) bad "top activity is '$t'" ;; +esac +if c=$(app_crashes); then + [ "${c:-0}" = 0 ] && ok "nothing in the crash buffer belongs to the app" || bad "$c crash entries mention the app" +else + bad "could not read the crash buffer" +fi + +if [ "$do_density" = 1 ] && [ -n "$orig_density" ]; then + head_ "Density change" + target=$((orig_density * 5 / 4)) + before=$(top_activity); pid0=$(app_pid) + sh_ logcat -b events -c >/dev/null + density_changed=1 + wm_status=0 + sh_ wm density "$target" >/dev/null || wm_status=$? + sleep 6 + applied=$(sh_ wm density) || wm_status=1 + after=$(top_activity); pid1=$(app_pid) + if [ "$wm_status" -ne 0 ] || [ "$(echo "$applied" | wm_override density)" != "$target" ]; then + bad "wm density failed" + else + if [ -n "$pid1" ] && [ "$pid0" = "$pid1" ]; then + ok "same process after $orig_density -> $target dpi" + else + bad "process changed ($pid0 -> $pid1)" + fi + case $before in "$pkg"/*) + n=$(relaunches_of "${before#*/}") + [ "${n:-0}" = 0 ] && ok "$before was not recreated" || bad "$before was recreated ${n}x" + [ "$after" = "$before" ] && ok "same top activity after the change" || bad "top activity changed ($before -> $after)" + ;; *) note "top activity was not the app ($before)" ;; esac + fi + if restore_density; then + density_changed=0 + else + bad "could not restore display density" + fi + sleep 3 +elif [ "$do_density" = 1 ]; then + note "could not read the original display density" +fi + +if [ "$do_size" = 1 ]; then + head_ "Window size change" + phys=$(echo "$size_snapshot" | sed -n 's/.*Physical size: \([0-9]*\)x\([0-9]*\).*/\1 \2/p' | head -1) + set -- $phys + if [ -n "${1:-}" ]; then + w=$(( ($2 * 2 / 3) / 2 * 2 )); h=$1 # a narrower, taller window, like a cover screen + pid0=$(app_pid) + size_changed=1 + wm_status=0 + sh_ wm size "${w}x${h}" >/dev/null || wm_status=$? + sleep 6 + applied=$(sh_ wm size) || wm_status=1 + pid1=$(app_pid) + if [ "$wm_status" -ne 0 ] || [ "$(echo "$applied" | wm_override size)" != "${w}x${h}" ]; then + bad "wm size failed" + elif [ -n "$pid1" ] && [ "$pid0" = "$pid1" ]; then + ok "same process at ${w}x${h}" + else + bad "process changed ($pid0 -> $pid1)" + fi + if restore_size; then + size_changed=0 + else + bad "could not restore window size" + fi + sleep 3 + else + note "could not read the physical size" + fi +fi + +if [ "$do_fold" = 1 ]; then + head_ "Foldable states" + states=$(sh_ cmd device_state print-states 2>/dev/null) + if ! echo "$states" | grep -q "identifier"; then + note "no device_state service (not a foldable, or not permitted)" + elif [ -z "$orig_state" ]; then + note "could not read the current device_state identifier" + else + id_of() { echo "$states" | sed -n "s/.*identifier=\([0-9]*\), name='$1'.*/\1/p" | head -1; } + half=$(id_of HALF_OPENED); closed=$(id_of CLOSED) + cycle() { # $1 name $2 id + pid0=$(app_pid) + fold_changed=1 + sh_ cmd device_state state "$2" >/dev/null; sleep 8 + got=$(sh_ cmd device_state state | sed -n "s/.*Committed state: DeviceState{identifier=[0-9]*, name='\([A-Z_]*\)'.*/\1/p" | head -1) + pid1=$(app_pid) + [ "$got" = "$1" ] && ok "device state is $1" || note "asked for $1, committed '$got'" + [ -n "$pid1" ] && [ "$pid0" = "$pid1" ] && ok "same process in $1" || bad "process changed in $1 ($pid0 -> $pid1)" + restore_fold; sleep 6 + } + if [ -n "$half" ]; then cycle HALF_OPENED "$half"; else note "no HALF_OPENED state"; fi + if [ "$do_closed" = 1 ] && [ -n "$closed" ]; then + cycle CLOSED "$closed" + note "CLOSED turns the screens off: the session pauses (Background behaviour), Resume it from the app" + fi + got=$(sh_ cmd device_state state | sed -n "s/.*Committed state: DeviceState{identifier=\([0-9]*\),.*/\1/p" | head -1) + [ "$got" = "$orig_state" ] && ok "device state restored ($orig_state)" || bad "device state is $got, was $orig_state" + fi +fi + +head_ "Session log (debug builds)" +dir=$(sh_ run-as "$pkg" ls -t files/logs 2>/dev/null | head -1) +if [ -z "$dir" ] || echo "$dir" | grep -q -i "not debuggable\|unknown package"; then + note "no readable session folder (release build, or no session has run)" +else + echo " newest session $dir" + ev=$(sh_ run-as "$pkg" cat "files/logs/$dir/events.jsonl" 2>/dev/null) + echo "$ev" | grep -q '"frame.first"' && ok "first frame was drawn" || note "no frame.first in $dir" + echo "$ev" | grep -q '"session.failed"' && bad "session.failed: $(echo "$ev" | grep '"session.failed"' | tail -1 | cut -c1-160)" + fps=$(sh_ run-as "$pkg" cat "files/logs/$dir/app.log" 2>/dev/null | grep 'last 10 s:' | tail -1 | sed 's/.*last 10 s: //' | cut -c1-70) + [ -n "$fps" ] && echo " last stats $fps" + sh_ run-as "$pkg" cat "files/logs/$dir/device.txt" 2>/dev/null | grep -E 'Memory page size|^Kernel' | sed 's/^/ report /' +fi + +[ "$fail" = 0 ] diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index 2f9aac03f2..a34e97e356 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -66,3 +66,22 @@ library list, before anything is published. Sixteen more of Armada's patches are DRM/lease/HDR-on-KMS work for a native display, which this app's Wayland-hosted gamescope never reaches, or need a newer gamescope than the runtime has. + +- `0116-release-cursor-shm-buffers.patch` - this app: pointer cursor surfaces have no + X11/xdg window association, so routing their commits through `g_PendingCommits` + retained every old SHM buffer until the surface was destroyed. Ignore cursor-role + commits before taking the buffer lock; X11 cursor images still follow the existing + MouseCursor path. Window commits awaiting association are unchanged. + +The live regression probe is `tools/tests/test_gamescope_cursor_shm.py`. Run it +inside an active Gamescope session with access to that process's `/proc` fd +directory. It submits 20 distinct SHM cursor buffers and requires at most the +current buffer to remain open, then none after surface destruction. The +`--unassigned-control` variant omits the cursor role and verifies that all 20 +commits awaiting a window association remain queued until surface destruction. + +Device validation (2026-10-20): the stock component retained 20/20 cursor buffers; +the patched component retained 1/20, then 0 after destruction. The unassigned +control retained 20/20 and then 0. In Backpack Battles, two batches of ten touch +drags leaked 188 and 197 SHM descriptors before the fix; the same batches added +zero after the fix (112 total descriptors before and after each batch). diff --git a/tools/gamescope/patches/0116-release-cursor-shm-buffers.patch b/tools/gamescope/patches/0116-release-cursor-shm-buffers.patch new file mode 100644 index 0000000000..03b4d7fd0c --- /dev/null +++ b/tools/gamescope/patches/0116-release-cursor-shm-buffers.patch @@ -0,0 +1,15 @@ +--- a/src/wlserver.cpp ++++ b/src/wlserver.cpp +@@ -203,6 +203,12 @@ + } + + void xwayland_surface_commit(struct wlr_surface *wlr_surface) { ++ // Cursor surfaces never acquire an X11/xdg window association. Keeping their ++ // commits in g_PendingCommits pins every old SHM buffer until the cursor ++ // surface is destroyed. X11 cursor images are handled by MouseCursor. ++ if ( wlr_surface->role && strcmp( wlr_surface->role->name, "wl_pointer-cursor" ) == 0 ) ++ return; ++ + wlr_surface->current.committed = 0; + + wlserver_x11_surface_info *wlserver_x11_surface_info = get_wl_surface_info(wlr_surface)->x11_surface; diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index 39ee3c8a61..236ff8598e 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -3,7 +3,7 @@ set -u export HOME=${HOME:-/root} mode=${1:-desktop} shift || true -step() { echo "== STEP $(date -u +%H:%M:%S) $*"; } +step() { echo "== STEP $(date -u +%H:%M:%S.%3N) $*"; } steam_setup_failed() { echo "== steam: the Steam client could not be set up (status $1)" [ -z "${BL_STEAM_EXIT_FILE:-}" ] || printf '%s\n' "$1" > "$BL_STEAM_EXIT_FILE" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat index 7ed1eb71eb..3972faa9b3 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat @@ -182,6 +182,20 @@ SWITCH_JS = r""" })() """.replace("__BINDING__", SWITCH_BINDING) SESSION_SELECT = "/usr/bin/steamos-session-select" +# Steam opens its Steam Controller welcome tour at every start while the client setting +# controller_show_ibex_tour (CMsgClientSettings field 140014) is on, and only a finished tour turns it +# off; closing it leaves it on. The app's pad is an emulated controller, so the tour never applies. +# A pending firmware update still opens Steam's updater, which checks the update priority instead. +TOUR_JS = r""" +(() => { + let key = 140014 * 8; + const bytes = []; + while (key > 127) { bytes.push((key & 127) | 128); key = Math.floor(key / 128); } + bytes.push(key, 0); + SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes))); + return "off"; +})() +""" VR_BINDING = "droiddeckLaunchSteamVr" VR_HELPER = "/usr/local/bin/droiddeck-steamvr" VR_JS = r""" @@ -528,6 +542,11 @@ class Helper: page.call("Runtime.addBinding", {"name": BINDING}) page.call("Runtime.addBinding", {"name": VR_BINDING}) page.evaluate(VR_JS) + try: + page.evaluate(TOUR_JS) + except RuntimeError: + # The optional tour setting must not block the compat bridge. + pass if not self.steamos: page.call("Runtime.addBinding", {"name": SWITCH_BINDING}) page.evaluate(SWITCH_JS) diff --git a/tools/release/authorship_hook.py b/tools/release/authorship_hook.py new file mode 100644 index 0000000000..3129f76153 --- /dev/null +++ b/tools/release/authorship_hook.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +import os +from pathlib import Path +import subprocess +import sys + +from check_authorship import BOT, COAUTHOR, check_revision + + +def main(): + hook, *args = sys.argv[1:] + payload = sys.stdin.buffer.read() if hook == "pre-push" else None + if hook == "pre-push": + checked = set() + for line in payload.decode().splitlines(): + local_ref, local_sha, _, _ = line.split() + if local_sha == "0" * 40 or local_sha in checked: + continue + checked.add(local_sha) + _, errors = check_revision(local_sha) + if errors: + print("\n".join(errors), file=sys.stderr) + return 1 + else: + identity = subprocess.check_output(["git", "var", "GIT_AUTHOR_IDENT"], text=True) + if BOT.search(identity): + print("Bot commit author is forbidden: " + identity.strip(), file=sys.stderr) + return 1 + message = Path(args[0]) + original = message.read_text(encoding="utf-8") + cleaned = "".join(line for line in original.splitlines(keepends=True) + if not (COAUTHOR.match(line) and BOT.search(line))) + if cleaned != original: + message.write_text(cleaned, encoding="utf-8") + print("Removed bot co-author trailers; human credits preserved.", file=sys.stderr) + legacy = Path(__file__).with_name("legacy-" + hook) + if legacy.exists() and os.access(legacy, os.X_OK): + return subprocess.run([str(legacy), *args], input=payload).returncode + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/release/check_authorship.py b/tools/release/check_authorship.py new file mode 100644 index 0000000000..9d952acc0d --- /dev/null +++ b/tools/release/check_authorship.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Reject bot authors and bot co-author trailers without executing reviewed code.""" +import argparse +import json +import re +import subprocess +import sys + +BOT = re.compile( + r"Claude|Anthropic|OpenAI|ChatGPT|GPT|Copilot|Cursor|Gemini|Codex|Devin|" + r"Windsurf|Codeium|Amazon Q|Tabnine|Cody|\[bot\]|github-actions|" + r"dependabot|renovate(?:\[bot\])?", + re.IGNORECASE, +) +COAUTHOR = re.compile(r"^\s*Co-authored-by\s*:", re.IGNORECASE) + + +def commit_violations(commit, raw): + header, separator, message = raw.partition(b"\n\n") + if not separator: + return [f"{commit}: invalid commit object"] + authors = [line[7:] for line in header.splitlines() if line.startswith(b"author ")] + if len(authors) != 1: + return [f"{commit}: expected one author"] + identity = authors[0].decode("utf-8", errors="replace") + errors = [] + if BOT.search(identity): + errors.append(f"{commit}: bot author: {identity}") + for line in message.decode("utf-8", errors="replace").splitlines(): + if COAUTHOR.match(line) and BOT.search(line): + errors.append(f"{commit}: bot co-author: {line.strip()}") + return errors + + +def event_violations(event): + pr = event.get("pull_request", {}) + user = pr.get("user", {}) + errors = [] + if user.get("type") == "Bot" or BOT.search(user.get("login", "")): + errors.append("pull request: bot authorship is forbidden") + for field in ("title", "body"): + for line in (pr.get(field) or "").splitlines(): + if COAUTHOR.match(line) and BOT.search(line): + errors.append(f"pull request {field}: bot co-author trailer") + return errors + + +def check_revision(revision): + commits = subprocess.check_output(["git", "rev-list", revision], text=True).splitlines() + errors = [] + with subprocess.Popen(["git", "cat-file", "--batch"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) as process: + for commit in commits: + process.stdin.write((commit + "\n").encode("ascii")) + process.stdin.flush() + descriptor = process.stdout.readline().split() + if len(descriptor) != 3 or descriptor[1] != b"commit": + raise RuntimeError(f"Cannot read commit {commit}") + size = int(descriptor[2]) + raw = process.stdout.read(size) + if len(raw) != size or process.stdout.read(1) != b"\n": + raise RuntimeError(f"Truncated commit {commit}") + errors.extend(commit_violations(commit, raw)) + process.stdin.close() + if process.wait() != 0: + raise RuntimeError("git cat-file failed") + return commits, errors + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("revision") + parser.add_argument("--event") + args = parser.parse_args() + commits, errors = check_revision(args.revision) + if args.event: + with open(args.event, encoding="utf-8") as source: + errors.extend(event_violations(json.load(source))) + for error in errors: + print(f"::error::{error}", file=sys.stderr) + if errors: + return 1 + print(f"Human authorship verified for {len(commits)} commits.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/release/install_authorship_hooks.py b/tools/release/install_authorship_hooks.py new file mode 100644 index 0000000000..dae4eb5177 --- /dev/null +++ b/tools/release/install_authorship_hooks.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Install shared worktree hooks while preserving existing executable hooks.""" +from pathlib import Path +import shutil +import subprocess + +MARKER = "# DroidDeck human authorship hook" + + +def install(): + common = Path(subprocess.check_output(["git", "rev-parse", "--git-common-dir"], text=True).strip()).resolve() + configured = subprocess.run(["git", "config", "--get", "core.hooksPath"], capture_output=True, text=True) + hooks = Path(configured.stdout.strip()).resolve() if configured.returncode == 0 else common / "hooks" + target = common / "authorship-hooks" + hooks.mkdir(parents=True, exist_ok=True) + target.mkdir(parents=True, exist_ok=True) + for name in ("check_authorship.py", "authorship_hook.py"): + shutil.copyfile(Path(__file__).with_name(name), target / name) + for name in ("prepare-commit-msg", "commit-msg", "pre-push"): + path = hooks / name + if path.exists() and MARKER not in path.read_text(errors="replace"): + legacy = target / ("legacy-" + name) + if legacy.exists(): + raise RuntimeError(f"Refusing to replace existing saved hook: {legacy}") + shutil.copy2(path, legacy) + path.write_text( + '#!/bin/sh\n' + MARKER + '\n' + 'exec python3 "$(git rev-parse --git-common-dir)/authorship-hooks/authorship_hook.py" ' + + name + ' "$@"\n' + ) + path.chmod(0o755) + print(f"Human authorship hooks installed in {hooks}") + + +if __name__ == "__main__": + install() diff --git a/tools/release/validate_apk.py b/tools/release/validate_apk.py new file mode 100644 index 0000000000..8ed51ebf19 --- /dev/null +++ b/tools/release/validate_apk.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Publish the APK result only after trusted source and metadata validation.""" +import json +import os +import subprocess +from urllib.parse import urlencode + +from check_authorship import check_revision, event_violations + + +def api(path, *args): + return json.loads(subprocess.check_output(["gh", "api", path, *args], text=True)) + + +def compilation_state(run, jobs): + for job in jobs: + if job["name"] in ("Compile and test APK", "Build APK"): + if job["status"] != "completed": + return "pending" + return "success" if job["conclusion"] == "success" else "failure" + return "failure" if run["status"] == "completed" else "pending" + + +def fetch_source(ref, sha): + subprocess.run(["git", "fetch", "--no-tags", "origin", ref], check=True) + fetched = subprocess.check_output(["git", "rev-parse", "FETCH_HEAD"], text=True).strip() + if fetched != sha: + raise RuntimeError("Pull request changed while validating") + + +def documentation_only(sha): + base = subprocess.check_output(["git", "merge-base", "origin/main", sha], text=True).strip() + paths = subprocess.check_output(["git", "diff", "--no-renames", "--name-only", "-z", base, sha]).split(b"\0") + return all(path.endswith(b".md") or path in (b"LICENSE", b".gitignore") for path in paths if path) + + +def main(): + with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as source: + event = json.load(source) + repo = os.environ["GITHUB_REPOSITORY"] + event_name = os.environ["GITHUB_EVENT_NAME"] + pr_number = event.get("number") if event_name == "pull_request_target" else None + if event_name == "workflow_dispatch": + pr_number = int(event.get("inputs", {}).get("pr_number") or 0) + run = event.get("workflow_run", {}) + expected = event.get("pull_request", {}).get("head", {}).get("sha") + if event_name == "workflow_run": + expected = run["head_sha"] + if run["event"] == "pull_request": + prs = api(f"repos/{repo}/commits/{expected}/pulls") + pr_number = next((pr["number"] for pr in prs + if pr["state"] == "open" and pr["head"]["sha"] == expected), None) + if pr_number is None: + print("Ignoring a superseded or closed pull request build") + return + elif run["head_branch"] != event["repository"]["default_branch"]: + return + if pr_number: + pr = api(f"repos/{repo}/pulls/{pr_number}") + sha = pr["head"]["sha"] + if pr["state"] != "open" or (expected and sha != expected): + print("Ignoring a superseded or closed pull request event") + return + ref = f"refs/pull/{pr_number}/head" + source_event = "pull_request" + else: + pr = None + sha = expected or event.get("after") or os.environ["GITHUB_SHA"] + ref = sha + source_event = "push" + state = "failure" + description = "APK source validation failed" + target = f"https://github.com/{repo}/actions/runs/{os.environ['GITHUB_RUN_ID']}" + try: + fetch_source(ref, sha) + commits, errors = check_revision(sha) + if pr: + errors.extend(event_violations({"pull_request": pr})) + if errors: + raise RuntimeError("\n".join(errors)) + print(f"Source and metadata validated for {len(commits)} commits") + if pr and documentation_only(sha): + state = "success" + description = "Source validated; no APK source changes" + return + query = urlencode({"head_sha": sha, "event": source_event, "per_page": 20}) + runs = api(f"repos/{repo}/actions/workflows/build.yml/runs?{query}")["workflow_runs"] + runs = [item for item in runs if item["head_sha"] == sha] + if runs: + latest = max(runs, key=lambda item: item["id"]) + jobs = api(f"repos/{repo}/actions/runs/{latest['id']}/jobs?per_page=100")["jobs"] + state = compilation_state(latest, jobs) + target = latest["html_url"] + else: + state = "pending" + description = {"pending": "Source validated; awaiting APK compilation", + "success": "Source validation and APK compilation passed", + "failure": "APK compilation failed"}[state] + finally: + api(f"repos/{repo}/statuses/{sha}", "--method", "POST", + "-f", "context=Build APK", "-f", f"state={state}", + "-f", f"description={description}", "-f", f"target_url={target}") + + +if __name__ == "__main__": + main() diff --git a/tools/tests/test_authorship.py b/tools/tests/test_authorship.py new file mode 100644 index 0000000000..03d0003b04 --- /dev/null +++ b/tools/tests/test_authorship.py @@ -0,0 +1,83 @@ +import importlib.util +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +path = Path(__file__).resolve().parents[1] / "release/check_authorship.py" +spec = importlib.util.spec_from_file_location("check_authorship", path) +check = importlib.util.module_from_spec(spec) +spec.loader.exec_module(check) + + +class AuthorshipTest(unittest.TestCase): + def commit(self, author="Human Contributor ", message="Fix a bug\n"): + return (f"tree {'0' * 40}\nauthor {author} 1 +0000\n" + "committer GitHub 1 +0000\n\n" + message).encode() + + def test_bot_primary_author_is_rejected_without_a_trailer(self): + for author in ("OpenAI Codex ", "Claude ", + "github-actions[bot] "): + with self.subTest(author=author): + self.assertTrue(check.commit_violations("abc", self.commit(author=author))) + + def test_bot_trailers_are_rejected_even_after_human_trailers(self): + message = "Fix\n\nCo-authored-by: Resul Övür \nco-AUTHORED-by: OpenAI Codex \n" + self.assertEqual(1, len(check.commit_violations("abc", self.commit(message=message)))) + + def test_human_authors_and_human_coauthors_are_preserved(self): + message = "Fix the Codex configuration\n\nCo-authored-by: Resul Övür \n" + self.assertEqual([], check.commit_violations("abc", self.commit(message=message))) + + def test_record_separator_in_message_does_not_hide_a_bot_trailer(self): + self.assertTrue(check.commit_violations("abc", self.commit(message="Fix\x1e\nCo-authored-by: Claude \n"))) + + def test_pr_metadata_cannot_add_a_bot_to_the_squash_message(self): + for field in ("title", "body"): + self.assertTrue(check.event_violations({"pull_request": {field: "Co-authored-by: Copilot "}})) + + def test_bot_pr_author_is_rejected(self): + self.assertTrue(check.event_violations({"pull_request": {"user": {"login": "service", "type": "Bot"}}})) + + def test_missing_author_fails_closed(self): + self.assertTrue(check.commit_violations("abc", b"tree 000\n\nmessage\n")) + + +class InstalledHooksTest(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.repo = Path(self.directory.name) + self.git("init", "-q") + self.git("config", "user.name", "Human Contributor") + self.git("config", "user.email", "human@example.com") + installer = path.with_name("install_authorship_hooks.py") + subprocess.run([sys.executable, str(installer)], cwd=self.repo, check=True, capture_output=True) + (self.repo / "file").write_text("content") + self.git("add", "file") + + def tearDown(self): + self.directory.cleanup() + + def git(self, *args): + return subprocess.run(["git", *args], cwd=self.repo, text=True, capture_output=True) + + def test_explicit_bot_author_override_is_blocked(self): + result = self.git("commit", "--author=OpenAI Codex ", "-m", "Fix") + self.assertNotEqual(0, result.returncode, result.stdout + result.stderr) + self.assertIn("Bot commit author is forbidden", result.stderr) + + def test_no_verify_does_not_skip_automatic_trailer_scrubbing(self): + result = self.git("commit", "--no-verify", "-m", "Fix\n\nCo-authored-by: Another Human \nCo-authored-by: Claude ") + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + message = self.git("log", "-1", "--format=%B").stdout + self.assertNotIn("noreply@anthropic.com", message) + self.assertIn("Co-authored-by: Another Human ", message) + + def test_human_commit_and_human_coauthor_are_allowed(self): + result = self.git("commit", "-m", "Fix\n\nCo-authored-by: Another Human ") + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_device_smoke.py b/tools/tests/test_device_smoke.py new file mode 100644 index 0000000000..9afeb919f9 --- /dev/null +++ b/tools/tests/test_device_smoke.py @@ -0,0 +1,123 @@ +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "device-smoke.sh" +FAKE_ADB = r'''#!/usr/bin/env python3 +import json, os, shlex, sys +from pathlib import Path +p = Path(os.environ["SMOKE_STATE"]) +s = json.loads(p.read_text()) +a = sys.argv[1:] +if a == ["get-state"]: + print("device") +elif a[:1] == ["shell"]: + a = shlex.split(a[1]) + if a[:1] == ["wm"]: + kind = a[1] + if len(a) == 2: + if s.get("unreadable") == kind: + print("permission denied") + else: + print("Physical " + kind + ": " + ("400" if kind == "density" else "1080x1920")) + if s.get(kind): print("Override " + kind + ": " + s[kind]) + else: + value = a[2] + s["writes"].append([kind, value]) + restoring = value in ("reset", "420", "1000x1800") + if not (s.get("ignored") == kind or restoring and s.get("restore_ignored") == kind): + s[kind] = "" if value == "reset" else value + p.write_text(json.dumps(s)) + elif a[:1] == ["getconf"]: print("4096") + elif a[:1] == ["pidof"]: print("123") + elif a[:2] == ["dumpsys", "activity"]: + print("topResumedActivity=ActivityRecord{abc u0 com.droiddeck.launcher/.MainActivity t1}") + elif a[:3] == ["pm", "list", "packages"]: + if s.get("query_failed"): sys.exit(1) + print("package:" + s.get("package", "com.droiddeck.launcher")) + elif a[:2] == ["am", "start"] and s.get("launch_failed"): + print("Error: activity could not be started") + sys.exit(1 if s["launch_failed"] == "exit" else 0) + elif a[:1] == ["run-as"]: + if s.get("session"): + s.setdefault("log_commands", []).append(a) + p.write_text(json.dumps(s)) + if "ls" in a: print(s["session"]) + else: print("package not debuggable") +''' + + +class DeviceSmokeTest(unittest.TestCase): + def run_smoke(self, **scenario): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + adb = root / "adb" + adb.write_text(FAKE_ADB) + adb.chmod(0o755) + sleep = root / "sleep" + sleep.write_text("#!/bin/sh\nexit 0\n") + sleep.chmod(0o755) + state = root / "state.json" + state.write_text(json.dumps({"density": "", "size": "", "writes": [], **scenario})) + env = dict(os.environ, ADB=str(adb), SMOKE_STATE=str(state), PATH=str(root) + os.pathsep + os.environ["PATH"]) + result = subprocess.run(["bash", str(SCRIPT), "--no-fold"], env=env, capture_output=True, text=True, timeout=30) + return result, json.loads(state.read_text()) + + def test_restores_preexisting_display_overrides(self): + result, state = self.run_smoke(density="420", size="1000x1800") + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + self.assertEqual("420", state["density"]) + self.assertEqual("1000x1800", state["size"]) + + def test_ignored_display_changes_do_not_pass(self): + for kind in ("density", "size"): + with self.subTest(kind=kind): + result, state = self.run_smoke(ignored=kind) + self.assertEqual(1, result.returncode, result.stdout) + self.assertIn("wm " + kind + " failed", result.stdout) + self.assertNotIn("PASS same process " + ("after" if kind == "density" else "at"), result.stdout) + self.assertEqual("", state[kind]) + + def test_ignored_restore_remains_a_failure_and_is_retried_on_exit(self): + for kind in ("density", "size"): + with self.subTest(kind=kind): + result, state = self.run_smoke(restore_ignored=kind) + self.assertEqual(1, result.returncode, result.stdout) + self.assertIn("could not restore", result.stdout) + self.assertNotEqual("", state[kind]) + self.assertEqual(2, state["writes"].count([kind, "reset"])) + + def test_unreadable_original_settings_are_not_changed(self): + for kind in ("density", "size"): + with self.subTest(kind=kind): + result, state = self.run_smoke(unreadable=kind) + self.assertEqual(0, result.returncode, result.stdout) + self.assertFalse(any(item[0] == kind for item in state["writes"])) + + def test_package_filter_does_not_accept_another_variant_or_a_failed_query(self): + for scenario in ({"package": "com.droiddeck.launcher.debug"}, {"query_failed": True}): + with self.subTest(scenario=scenario): + result, state = self.run_smoke(**scenario) + self.assertEqual(2, result.returncode, result.stdout) + self.assertEqual([], state["writes"]) + + def test_failed_launch_is_not_masked_by_an_existing_process(self): + for failure in ("exit", "message"): + with self.subTest(failure=failure): + result, _ = self.run_smoke(launch_failed=failure) + self.assertEqual(1, result.returncode, result.stdout) + self.assertIn("could not launch", result.stdout) + + def test_session_name_remains_one_remote_argument(self): + session = "x';id;#" + result, state = self.run_smoke(session=session) + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + self.assertIn(["run-as", "com.droiddeck.launcher", "cat", "files/logs/" + session + "/events.jsonl"], state["log_commands"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_gamescope_cursor_shm.py b/tools/tests/test_gamescope_cursor_shm.py new file mode 100644 index 0000000000..35ca27acb2 --- /dev/null +++ b/tools/tests/test_gamescope_cursor_shm.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Live regression probe; run inside a running Gamescope session. + +Requires Python 3, WAYLAND_DISPLAY, XDG_RUNTIME_DIR and access to Gamescope's +/proc//fd. Creates only a temporary surface with the cursor role; it does +not take pointer focus or change game/save files. Affected Gamescope retains all +20 SHM allocations; fixed Gamescope retains at most the current cursor buffer. +""" +import os +import socket +import struct +import time +import json +import array +import argparse +from pathlib import Path + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--unassigned-control', action='store_true', help='verify that window buffers awaiting association remain queued') + args = parser.parse_args() + s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + s.settimeout(2) + s.connect(os.path.join(os.environ['XDG_RUNTIME_DIR'], os.environ['WAYLAND_DISPLAY'])) + U = lambda *v: struct.pack('<' + 'I' * len(v), *v) + + def string(v): + b = v.encode() + b'\x00' + return U(len(b)) + b + b'\x00' * (-len(b) % 4) + + def send(obj, op, p=b'', fd=None): + b = U(obj, len(p) + 8 << 16 | op) + p + if fd is None: + s.sendall(b) + else: + s.sendmsg([b], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array('i', [fd]))]) + nextid = 2 + pids = [] + for process in Path('/proc').iterdir(): + if not process.name.isdigit(): + continue + try: + if (process / 'comm').read_text().strip() == 'gamescope': + pids.append(process) + except (FileNotFoundError, PermissionError): + pass + assert len(pids) == 1, f'expected one Gamescope process, found {[p.name for p in pids]}' + fd_dir = pids[0] / 'fd' + + def alloc(): + nonlocal nextid + nextid += 1 + return nextid + pending = b'' + globals = {} + + def roundtrip(): + nonlocal pending + cb = alloc() + send(1, 0, U(cb)) + while True: + while len(pending) >= 8: + obj, h = struct.unpack_from('> 16 + op = h & 65535 + if len(pending) < n: + break + p = pending[8:n] + pending = pending[n:] + if obj == 1 and op == 0: + raise RuntimeError('wayland error ' + repr(p)) + if obj == 2 and op == 0: + name, l = struct.unpack_from('