From 3331edf265f694aac510114edf8a70784b39ad68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Resul=20=C3=96v=C3=BCr?= <92828257+ovurrsl@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:40:48 +0300 Subject: [PATCH 01/10] perf: session log step times carry milliseconds (#993) The == STEP lines in session.log now read HH:MM:SS.mmm, so the setup steps before Steam starts can be timed; with whole seconds most of them showed the same time. Co-authored-by: ovurrsl Co-authored-by: xXJsonDeruloXx --- .../overlay/usr/local/bin/droiddeck-session | 2 +- tools/tests/test_session_step_time.py | 27 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 tools/tests/test_session_step_time.py 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/tests/test_session_step_time.py b/tools/tests/test_session_step_time.py new file mode 100644 index 0000000000..2622e34ccd --- /dev/null +++ b/tools/tests/test_session_step_time.py @@ -0,0 +1,27 @@ +import re +import subprocess +import unittest +from pathlib import Path + +SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session" + + +def step_function(): + match = re.search(r"^step\(\) \{.*\}$", SESSION.read_text(), re.M) + return match.group(0) + + +class SessionStepTimeTest(unittest.TestCase): + def test_a_step_line_carries_milliseconds_before_its_text(self): + out = subprocess.run(["bash", "-c", step_function() + "\nstep starting the Steam client"], + capture_output=True, text=True, timeout=30).stdout.strip() + self.assertRegex(out, r"^== STEP \d{2}:\d{2}:\d{2}\.\d{3} starting the Steam client$") + + def test_the_text_after_the_first_space_is_the_step_name(self): + out = subprocess.run(["bash", "-c", step_function() + "\nstep checking the Steam client"], + capture_output=True, text=True, timeout=30).stdout.strip() + self.assertEqual("checking the Steam client", out.removeprefix("== STEP ").split(" ", 1)[1]) + + +if __name__ == "__main__": + unittest.main() From 8ed98b570b9a746107259c37625dc2b3a74a82f7 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 22 Oct 2026 10:42:57 -0400 Subject: [PATCH 02/10] Keep visible external-display sessions running (#1320) Track visibility on the activity display Separate activity visibility from the compositor display so a powered external screen keeps the session visible when the handset is locked. Notify the service as the activity moves between displays and avoid reporting a removed host display before Android moves the activity. --- .../com/droiddeck/launcher/SessionActivity.kt | 47 +++++++++++-- .../launcher/session/SessionService.kt | 67 +++++++++++++++++-- .../launcher/session/SessionState.kt | 2 + .../session/SessionVisibilityPolicy.kt | 15 +++++ .../session/SessionVisibilityPolicyTest.kt | 27 ++++++++ 5 files changed, 145 insertions(+), 13 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/session/SessionVisibilityPolicy.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/SessionVisibilityPolicyTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index ace8b51f28..f2d2e747b8 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -366,17 +366,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 @@ -1678,7 +1707,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 +1758,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() @@ -2888,11 +2919,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 +2938,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 +2969,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/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/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)) + } +} From 3c622a932391cc9b111315ece4b5717b34c9ca02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Resul=20=C3=96v=C3=BCr?= <92828257+ovurrsl@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:43:41 +0300 Subject: [PATCH 03/10] feat: the unfolded controls can stay while a controller is connected (#996) On foldables the unfolded-screen controls panel hides whenever a controller is connected (#829). Phones held in a telescopic controller still want its trackpads and back grips, so a new setting under "Controls on the unfolded screen" keeps the panel with a controller. It is off by default and appears in the launcher settings and the in-session menu while unfolded controls are on. The visibility decision moves into SessionDisplay.unfoldedControlsWanted with unit tests. Closes #861 Co-authored-by: ovurrsl Co-authored-by: xXJsonDeruloXx --- .../com/droiddeck/launcher/MainActivity.kt | 6 +++++ .../com/droiddeck/launcher/SessionActivity.kt | 26 ++++++++++++++---- .../launcher/session/SessionDisplay.kt | 13 +++++++++ .../launcher/session/SessionPrefs.kt | 7 +++++ .../launcher/session/SettingsReset.kt | 3 ++- .../launcher/ui/ModeSettingsDialog.kt | 7 +++++ .../droiddeck/launcher/ui/SessionOverlay.kt | 7 +++++ app/src/main/res/values-tr/strings.xml | 2 ++ app/src/main/res/values/strings.xml | 2 ++ .../launcher/session/SessionDisplayTest.kt | 27 +++++++++++++++++++ .../launcher/session/SettingsResetTest.kt | 2 ++ 11 files changed, 96 insertions(+), 6 deletions(-) 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 f2d2e747b8..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() { @@ -952,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() }, @@ -1436,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) @@ -2487,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() @@ -2496,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 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/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/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/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/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 03110445e7..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), diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 4f2442fb05..da288eb3ee 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -1159,6 +1159,8 @@ Otomatik olarak PiP moduna geç Açılmış ekrandaki kontroller Cihaz açıkken oyun, Steam Deck dokunmatik yüzeylerinin ve arka tutamaklarının üstünde durur. Katlıyken oyun tam ekran olur. + Kumanda bağlıyken de göster + Telefonu tutan kumandalar için, kumanda bağlıyken de açılmış ekrandaki kontrolleri gösterir. Askıya alındı Pencere içinde pencere, oturum hazır olduğunda kullanılabilir. Android ayarlarında DroidDeck için pencere içinde pencereye izin verin. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 2a41437dbb..312dcd2c79 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/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)) From e49557a02db408c140b2e769de4b239ad451b9cc Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 22 Oct 2026 10:47:12 -0400 Subject: [PATCH 04/10] fix: register Android CJK fonts with fontconfig (#1319) * fix: write CJK fontconfig as valid Kotlin * fix: choose CJK fonts for requested language * fix: prefer exact Chinese fontconfig locales --------- Co-authored-by: zooluis <150430329+zooluis@users.noreply.github.com> --- .../launcher/session/SessionFiles.kt | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) 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) + } + } } From 7bb1b5b74ba18aa9c25e0af7fdb3eaad50274b7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Resul=20=C3=96v=C3=BCr?= <92828257+ovurrsl@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:48:38 +0300 Subject: [PATCH 05/10] feat: tools/device-smoke.sh checks a build on a real device over plain adb (#911) * feat: tools/device-smoke.sh checks a build on a real device over plain adb Installs and launches the app, changes the density and the window size, cycles a foldable's device state, then reads the newest debug session (first frame, last frame rate, memory page size, process exits). It restores the display and the device state it changed. No python needed; complements tools/droiddeck-scenario, which drives games. * fix: device-smoke.sh restores only what it changed and checks more carefully Restore the device state by cancelling the override the script made, or by putting back the override that was already pinned (a test lab pins one), instead of pinning the committed state. Restore density and size only after the script changed them. Keep adb's exit status, count only crashes of the tested app and fail when the crash buffer cannot be read, compare the top activity after the density change, and exit 2 when an option value is missing. * fix: check wm density/size exit statuses and keep restore flags on failure * fix: verify smoke-test display changes and restoration * fix: reject false smoke-test launches and quote remote paths * Run final display cleanup before reporting smoke results --------- Co-authored-by: ovurrsl Co-authored-by: xXJsonDeruloXx --- tools/device-smoke.sh | 287 +++++++++++++++++++++++++++++++ tools/tests/test_device_smoke.py | 123 +++++++++++++ 2 files changed, 410 insertions(+) create mode 100755 tools/device-smoke.sh create mode 100644 tools/tests/test_device_smoke.py 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/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() From 4421e851dd11d2451934d862c60e377867506cd4 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 22 Oct 2026 11:12:41 -0400 Subject: [PATCH 06/10] Enforce human authorship with automatic trailer scrubbing (#1325) Install commit and push hooks that remove bot co-author trailers, preserve human credits, and reject bot primary authors. Add a trusted default-branch CI checker and publish its required status on the exact proposed commit. Validate main pushes as well. Ten regression tests pass, including real Git hook tests and the --no-verify case. --- .github/workflows/authorship.yml | 58 +++++++++++++++ .github/workflows/build.yml | 23 +++--- tools/release/authorship_hook.py | 43 +++++++++++ tools/release/check_authorship.py | 87 +++++++++++++++++++++++ tools/release/install_authorship_hooks.py | 36 ++++++++++ tools/tests/test_authorship.py | 83 +++++++++++++++++++++ 6 files changed, 321 insertions(+), 9 deletions(-) create mode 100644 .github/workflows/authorship.yml create mode 100644 tools/release/authorship_hook.py create mode 100644 tools/release/check_authorship.py create mode 100644 tools/release/install_authorship_hooks.py create mode 100644 tools/tests/test_authorship.py diff --git a/.github/workflows/authorship.yml b/.github/workflows/authorship.yml new file mode 100644 index 0000000000..4bbefa414b --- /dev/null +++ b/.github/workflows/authorship.yml @@ -0,0 +1,58 @@ +name: Human authorship + +on: + pull_request_target: + types: [opened, synchronize, reopened, edited, ready_for_review] + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + pull-requests: read + statuses: write + +jobs: + authorship: + name: Validate human authorship + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + fetch-depth: 0 + persist-credentials: false + - name: Check the proposed or merged history + id: validate + env: + GH_TOKEN: ${{ github.token }} + EVENT_NAME: ${{ github.event_name }} + PR_NUMBER: ${{ github.event.pull_request.number }} + BEFORE: ${{ github.event.before }} + AFTER: ${{ github.sha }} + PR_HEAD: ${{ github.event.pull_request.head.sha }} + run: | + set -euo pipefail + if [ "$EVENT_NAME" = pull_request_target ]; then + gh auth setup-git + git fetch --no-tags origin "refs/pull/$PR_NUMBER/head" + test "$(git rev-parse FETCH_HEAD)" = "$PR_HEAD" + base=$(git merge-base HEAD FETCH_HEAD) + python3 tools/release/check_authorship.py "$base..FETCH_HEAD" --event "$GITHUB_EVENT_PATH" + elif [ "$EVENT_NAME" = push ] && [ "$BEFORE" != 0000000000000000000000000000000000000000 ]; then + python3 tools/release/check_authorship.py "$BEFORE..$AFTER" + else + python3 tools/release/check_authorship.py HEAD + fi + - name: Publish the required result on the actual proposed commit + if: always() + env: + GH_TOKEN: ${{ github.token }} + TARGET_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RESULT: ${{ steps.validate.outcome == 'success' && 'success' || 'failure' }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + gh api --method POST "repos/$GITHUB_REPOSITORY/statuses/$TARGET_SHA" \ + -f context='Human authorship' -f state="$RESULT" -f target_url="$RUN_URL" \ + -f description='Bot authors and bot co-author trailers are forbidden' diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0dc1289e59..32ea61e34d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -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/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/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() From 3a09e5698beba8b97406ac378ea8007f0f828f87 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 22 Oct 2026 11:27:59 -0400 Subject: [PATCH 07/10] fix: stop Steam's Steam Controller welcome tour from opening on every boot (#1321) * fix: stop Steam's Steam Controller welcome tour from opening on every boot * fix steam tour failure not to block helper attach --- .../usr/local/bin/droiddeck-steam-compat | 19 +++++++++++++++++++ tools/tests/test_steam_compat_live.py | 16 ++++++++++++++++ 2 files changed, 35 insertions(+) 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/tests/test_steam_compat_live.py b/tools/tests/test_steam_compat_live.py index 3cf27824b4..a86aab8644 100644 --- a/tools/tests/test_steam_compat_live.py +++ b/tools/tests/test_steam_compat_live.py @@ -774,6 +774,14 @@ class AttachPage: return {"selected": "", "fallback": "", "tools": []} +class TourFailurePage(AttachPage): + def evaluate(self, expression, timeout=30): + self.scripts.append(expression) + if expression == LIVE["TOUR_JS"]: + raise RuntimeError("SteamClient.Settings.SetSetting is unavailable") + return True + + class SwitchToDesktopTest(unittest.TestCase): def setUp(self): self.globals = LIVE["Helper"].attach.__globals__ @@ -798,6 +806,14 @@ class SwitchToDesktopTest(unittest.TestCase): self.assertIn(("Runtime.addBinding", LIVE["VR_BINDING"]), helper.page.calls) self.assertIn(LIVE["VR_JS"], helper.page.scripts) + def test_missing_optional_tour_setting_does_not_block_attach(self): + with mock.patch.dict(self.globals, {"shared_context": lambda port: "/devtools/page/1", "Page": TourFailurePage}): + helper = LIVE["Helper"]("/steam", 1) + self.assertTrue(helper.attach()) + self.assertIn(LIVE["VR_JS"], helper.page.scripts) + self.assertIn(LIVE["TOUR_JS"], helper.page.scripts) + self.assertIsNotNone(helper.page) + def test_vr_bridge_accepts_only_steamvr_and_coalesces_requests(self): helper = LIVE["Helper"]("/steam", 1) helper.page = mock.Mock() From 701e70bd3edf2fef473dfe3f880000d4fb16b4c5 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 22 Oct 2026 11:43:05 -0400 Subject: [PATCH 08/10] fix: the emulated Steam Controller reports the firmware build Steam ships (#1323) * fix: the emulated Steam Controller reports the firmware build Steam ships * fix Triton firmware lookup for Steam root binary --- app/src/main/cpp/fakeinput_steam.cpp | 34 +++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) 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]; From 792a69ebfea6e879c5053d8b47d8ffcd32bb0b1b Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 22 Oct 2026 12:11:05 -0400 Subject: [PATCH 09/10] Combine authorship validation with the required APK result (#1329) Combine trusted source and squash-metadata validation with the exact-head APK compilation result. Preserve automatic trailer cleanup in the installed hooks. Validated with 10 authorship/hook tests and 9 combined-gate tests. --- .github/workflows/authorship.yml | 50 +++++---------- .github/workflows/build.yml | 2 +- tools/release/validate_apk.py | 106 ++++++++++++++++++++++++++++++ tools/tests/test_validate_apk.py | 107 +++++++++++++++++++++++++++++++ 4 files changed, 230 insertions(+), 35 deletions(-) create mode 100644 tools/release/validate_apk.py create mode 100644 tools/tests/test_validate_apk.py diff --git a/.github/workflows/authorship.yml b/.github/workflows/authorship.yml index 4bbefa414b..97c6637a8f 100644 --- a/.github/workflows/authorship.yml +++ b/.github/workflows/authorship.yml @@ -1,58 +1,40 @@ -name: Human authorship +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: - authorship: - name: Validate human authorship + validate: + name: Build APK runs-on: ubuntu-24.04 timeout-minutes: 5 steps: - uses: actions/checkout@v4 with: - ref: ${{ github.event.repository.default_branch }} + ref: ${{ github.workflow_sha }} fetch-depth: 0 persist-credentials: false - - name: Check the proposed or merged history - id: validate + - name: Validate source and APK compilation env: GH_TOKEN: ${{ github.token }} - EVENT_NAME: ${{ github.event_name }} - PR_NUMBER: ${{ github.event.pull_request.number }} - BEFORE: ${{ github.event.before }} - AFTER: ${{ github.sha }} - PR_HEAD: ${{ github.event.pull_request.head.sha }} run: | - set -euo pipefail - if [ "$EVENT_NAME" = pull_request_target ]; then - gh auth setup-git - git fetch --no-tags origin "refs/pull/$PR_NUMBER/head" - test "$(git rev-parse FETCH_HEAD)" = "$PR_HEAD" - base=$(git merge-base HEAD FETCH_HEAD) - python3 tools/release/check_authorship.py "$base..FETCH_HEAD" --event "$GITHUB_EVENT_PATH" - elif [ "$EVENT_NAME" = push ] && [ "$BEFORE" != 0000000000000000000000000000000000000000 ]; then - python3 tools/release/check_authorship.py "$BEFORE..$AFTER" - else - python3 tools/release/check_authorship.py HEAD - fi - - name: Publish the required result on the actual proposed commit - if: always() - env: - GH_TOKEN: ${{ github.token }} - TARGET_SHA: ${{ github.event.pull_request.head.sha || github.sha }} - RESULT: ${{ steps.validate.outcome == 'success' && 'success' || 'failure' }} - RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - run: | - gh api --method POST "repos/$GITHUB_REPOSITORY/statuses/$TARGET_SHA" \ - -f context='Human authorship' -f state="$RESULT" -f target_url="$RUN_URL" \ - -f description='Bot authors and bot co-author trailers are forbidden' + gh auth setup-git + python3 tools/release/validate_apk.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 32ea61e34d..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 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_validate_apk.py b/tools/tests/test_validate_apk.py new file mode 100644 index 0000000000..d197d74cff --- /dev/null +++ b/tools/tests/test_validate_apk.py @@ -0,0 +1,107 @@ +import contextlib +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +RELEASE = Path(__file__).resolve().parents[1] / "release" +sys.path.insert(0, str(RELEASE)) +import validate_apk + + +class ValidateApkTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + subprocess.run(["git", "init", "-q", self.root], check=True) + self.git("config", "user.name", "Human Developer") + self.git("config", "user.email", "human@example.org") + self.git("commit", "--allow-empty", "-qm", "Baseline") + self.git("update-ref", "refs/remotes/origin/main", "HEAD") + self.statuses = [] + + def git(self, *args): + return subprocess.check_output(["git", "-C", self.root, *args], text=True).strip() + + def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt"): + (self.root / filename).write_text(message) + self.git("add", filename) + self.git("commit", "--allow-empty", "-qm", message) + sha = self.git("rev-parse", "HEAD") + pr = {"number": 1, "state": "open", "head": {"sha": sha}, "user": {"login": "human", "type": "User"}, + "title": "Source change", "body": body} + event = {"number": 1, "pull_request": {"head": {"sha": "stale" if stale else sha}}} + if completed: + event = {"workflow_run": {"event": "pull_request", "head_sha": "stale" if stale else sha}} + path = self.root / "event.json" + path.write_text(json.dumps(event)) + + def api(path, *args): + if "/statuses/" in path: + self.statuses.append(dict(value.split("=", 1) for value in args if "=" in value)) + return {} + if path.endswith("/pulls/1"): + return pr + if "/commits/" in path and path.endswith("/pulls"): + return [pr] + if "workflows/build.yml/runs?" in path: + return {"workflow_runs": [{"id": 7, "head_sha": sha, "status": "completed", "html_url": "https://example.org/build"}]} + if path.endswith("/jobs?per_page=100"): + return {"jobs": [{"name": "Compile and test APK", "status": "in_progress" if result == "pending" else "completed", "conclusion": result}]} + raise AssertionError(path) + + env = {"GITHUB_EVENT_PATH": str(path), "GITHUB_REPOSITORY": "owner/repo", + "GITHUB_EVENT_NAME": "workflow_run" if completed else "pull_request_target", "GITHUB_RUN_ID": "8"} + with contextlib.chdir(self.root), patch.dict(os.environ, env), patch.object(validate_apk, "api", side_effect=api), patch.object(validate_apk, "fetch_source"): + validate_apk.main() + + def test_success_requires_compilation_and_clean_authorship(self): + self.validate() + self.assertEqual(self.statuses[-1]["state"], "success") + + def test_successful_build_cannot_hide_bot_commit(self): + with self.assertRaises(RuntimeError): + self.validate(message="Change\n\nCo-authored-by: OpenAI Codex ") + self.assertEqual(self.statuses[-1]["state"], "failure") + + def test_successful_build_cannot_hide_squash_metadata(self): + with self.assertRaises(RuntimeError): + self.validate(body="Co-authored-by: Claude ") + self.assertEqual(self.statuses[-1]["state"], "failure") + + def test_pending_or_failed_compilation_never_passes(self): + for result in ("pending", "failure"): + self.validate(result=result) + self.assertEqual(self.statuses[-1]["state"], result) + + def test_superseded_event_cannot_replace_current_status(self): + self.validate(stale=True) + self.assertEqual(self.statuses, []) + + def test_completed_build_revalidates_current_squash_metadata(self): + with self.assertRaises(RuntimeError): + self.validate(body="Co-authored-by: Claude ", completed=True) + self.assertEqual(self.statuses[-1]["state"], "failure") + + def test_superseded_build_cannot_replace_current_status(self): + self.validate(stale=True, completed=True) + self.assertEqual(self.statuses, []) + + def test_documentation_passes_without_waiting_for_a_skipped_build(self): + self.validate(filename="README.md", result="pending") + self.assertEqual(self.statuses[-1]["state"], "success") + + def test_renaming_code_to_documentation_still_requires_compilation(self): + (self.root / "source.kt").write_text("source") + self.git("add", "source.kt") + self.git("commit", "-qm", "Add source") + self.git("update-ref", "refs/remotes/origin/main", "HEAD") + self.git("mv", "source.kt", "README.md") + self.git("commit", "-qm", "Rename source") + with contextlib.chdir(self.root): + self.assertFalse(validate_apk.documentation_only(self.git("rev-parse", "HEAD"))) From e1a7d527fd412b6bd78833e01fe80f515e324971 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 22 Oct 2026 12:13:03 -0400 Subject: [PATCH 10/10] Update the nested KWin builder to 6.8.0 (#1328) Match the native builder and desktop package override to Arch Linux ARM KWin 6.8.0, pin the official source hash, and port the nested-scaling patch. Check package/source version consistency in both build jobs. Official source checksum, patch application, live package closure, and shell syntax verified. The published desktop remains pinned to r2; candidate 6.8 device/rendering validation remains pending before any package publication. --- tools/desktop-kde/README.md | 10 +- tools/desktop-kde/build-kwin.sh | 11 +- tools/desktop-kde/build.sh | 8 +- tools/desktop-kde/kwin.env | 1 + .../share/licenses/droiddeck-desktop/NOTICE | 4 +- .../0001-respect-nested-desktop-scale.patch | 224 ++++++++++-------- 6 files changed, 143 insertions(+), 115 deletions(-) create mode 100644 tools/desktop-kde/kwin.env 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;