From f13916ee25e6828659f768748f9f8e3d820354ac Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:51:44 -0400 Subject: [PATCH] feat(steam): optional Steam integration setup (#1637) * feat(steam): add optional device integration setup * feat(steam): show integration setup as inline settings rows * fix(steam): offer App info when shortcuts stay blocked --- app/src/main/AndroidManifest.xml | 9 + .../droiddeck/launcher/FrontEndActivity.kt | 100 ++++++-- .../com/droiddeck/launcher/SessionActivity.kt | 14 ++ .../launcher/core/SteamIntegration.kt | 72 ++++++ .../launcher/input/HomeButtonService.kt | 70 ++++++ .../launcher/input/HomeGuideInput.kt | 42 ++++ .../droiddeck/launcher/input/PadBridge.java | 38 +++- .../runtime/DeviceControlsComponent.kt | 31 +-- .../droiddeck/launcher/ui/FrontEndScreen.kt | 8 + .../droiddeck/launcher/ui/FrontEndSetup.kt | 3 + .../launcher/ui/ModeSettingsDialog.kt | 46 +--- .../droiddeck/launcher/ui/SettingsWidgets.kt | 3 +- .../com/droiddeck/launcher/ui/SteamHome.kt | 2 + .../launcher/ui/SteamIntegrationGroup.kt | 215 ++++++++++++++++++ app/src/main/res/values/strings.xml | 25 +- app/src/main/res/xml/home_button_service.xml | 7 + .../launcher/input/HomeGuideInputTest.kt | 62 +++++ .../launcher/input/PadBridgeQamTest.kt | 47 ++++ .../runtime/DeviceControlsComponentTest.kt | 20 +- .../launcher/ui/SteamIntegrationGroupTest.kt | 93 ++++++++ 20 files changed, 813 insertions(+), 94 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/input/HomeButtonService.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/input/HomeGuideInput.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt create mode 100644 app/src/main/res/xml/home_button_service.xml create mode 100644 app/src/test/java/com/droiddeck/launcher/input/HomeGuideInputTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 6336fb1325..8612604928 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -58,6 +58,15 @@ + + + + + + (null) private val wifiLocationReceiver = object : android.content.BroadcastReceiver() { override fun onReceive(context: android.content.Context?, intent: Intent?) { refreshWifiDiscovery() @@ -265,8 +268,65 @@ class FrontEndActivity : ComponentActivity() { SessionPrefs.setWifiDiscoveryEnabled(this, false) } wifiDiscovery = SessionPrefs.wifiDiscoveryEnabled(this) + integrationState = readIntegration() } + private var shortcutsTried = false + + private fun readIntegration() = SteamIntegration.read(this) + .copy(locationBlocked = wifiDiscoveryBlocked, shortcutsTried = shortcutsTried) + + private fun openIntegration(feature: SteamIntegration.Feature? = null) { + SteamIntegration.dismissSuggestion(this) + refreshWifiDiscovery() + integrationState = readIntegration() + integrationFocus = feature + navRequest = "setup:integration" + } + + private fun readIntegrationIntent(incoming: Intent) { + if (incoming.action != SteamIntegration.ACTION_SETUP) return + openIntegration(incoming.getStringExtra(SteamIntegration.EXTRA_FEATURE)?.let { + runCatching { SteamIntegration.Feature.valueOf(it) }.getOrNull() + }) + } + + private fun integrationSettings(intent: Intent, fallback: String = android.provider.Settings.ACTION_SETTINGS) { + try { startActivity(intent) } + catch (_: android.content.ActivityNotFoundException) { startActivity(Intent(fallback)) } + catch (_: SecurityException) { startActivity(Intent(fallback)) } + } + + private fun configureIntegration(feature: SteamIntegration.Feature) { + when (feature) { + SteamIntegration.Feature.WIFI -> { + if (wifiDiscovery && wifiDiscoveryPermission) { + SessionPrefs.setWifiDiscoveryEnabled(this, false) + } else if (wifiDiscoveryPermission) { + SessionPrefs.setWifiDiscoveryEnabled(this, true) + } else { + SessionPrefs.setWifiDiscoveryAsked(this) + wifiLocationPermission.launch(WifiDiscovery.permissions) + } + refreshWifiDiscovery() + } + SteamIntegration.Feature.BRIGHTNESS -> integrationSettings(SteamIntegration.brightnessSettings(this)) + SteamIntegration.Feature.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else { + HomeApp.setHomeScreenEnabled(this, true) + refreshHomeAppState() + manageHomeApp() + } + SteamIntegration.Feature.SHORTCUTS -> { + if (!integrationState.shortcuts) shortcutsTried = true + if (!HomeApp.isDefault(this)) configureIntegration(SteamIntegration.Feature.HOME) + else integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS) + } + } + } + + private fun openAppInfo() = + integrationSettings(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName"))) + private fun openWifiDiscoverySettings() { if (!WifiDiscovery.permissionGranted(this)) { wifiPermissionSettings.launch(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, @@ -839,6 +899,7 @@ class FrontEndActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + if (savedInstanceState == null) readIntegrationIntent(intent) readGameIntent(intent) gameSyncFolder = GameFileSync.folder(this) displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager @@ -905,6 +966,8 @@ class FrontEndActivity : ComponentActivity() { isHomeApp = homeAppSelected, homeScreenEnabled = homeScreenEnabled, defaultHomeLabel = defaultHomeLabel, + integration = integrationState, + integrationFocus = integrationFocus, androidApps = androidApps, secondScreenDisplays = secondScreenDisplays, packages = packageRows, @@ -1144,6 +1207,14 @@ class FrontEndActivity : ComponentActivity() { downloadProxy = DownloadSource.proxyHostPort(this) }, onHomeApp = { manageHomeApp() }, + onSteamIntegration = ::openIntegration, + onIntegration = { integrationFocus = null; configureIntegration(it) }, + onIntegrationAppInfo = ::openAppInfo, + onIntegrationLocation = ::openWifiDiscoverySettings, + onDismissIntegration = { + SteamIntegration.dismissSuggestion(this) + integrationState = readIntegration() + }, onHomeScreen = { on -> HomeApp.setHomeScreenEnabled(this, on) refreshHomeAppState() @@ -1336,6 +1407,10 @@ class FrontEndActivity : ComponentActivity() { override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) + if (intent.action == SteamIntegration.ACTION_SETUP) { + readIntegrationIntent(intent) + return + } readGameIntent(intent) refresh() startSteamAtStartupIfEnabled() @@ -1521,6 +1596,7 @@ class FrontEndActivity : ComponentActivity() { homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this) defaultHomeLabel = HomeApp.defaultLabel(this) androidApps = if (homeAppSelected) HomeApp.launchableApps(this) else emptyList() + integrationState = readIntegration() } private fun refreshSecondScreenDisplays() { @@ -1844,11 +1920,7 @@ class FrontEndActivity : ComponentActivity() { bootMovieCustomName = bootMovieCustomName, bootMovieImporting = bootMovieImporting, bootMovieProgress = bootMovieProgress, - wifiDiscovery = if (mode == SessionService.MODE_STEAM) wifiDiscovery else null, - wifiDiscoveryPermission = wifiDiscoveryPermission, - wifiDiscoveryLocation = wifiDiscoveryLocation, - wifiDiscoveryAsked = wifiDiscoveryAsked, - wifiDiscoveryBlocked = wifiDiscoveryBlocked, + integration = if (mode == SessionService.MODE_STEAM) integrationState else null, deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null, deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyLatest else null, deckyBranch = decky.deckyBranch, @@ -1857,21 +1929,9 @@ class FrontEndActivity : ComponentActivity() { deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running, ), ModeSettingsActions( - onWifiDiscovery = { on -> - if (!on) { - SessionPrefs.setWifiDiscoveryEnabled(this, false) - refreshWifiDiscovery() - } else if (WifiDiscovery.permissionGranted(this)) { - SessionPrefs.setWifiDiscoveryEnabled(this, true) - refreshWifiDiscovery() - } else if (wifiDiscoveryBlocked) { - openWifiDiscoverySettings() - } else { - SessionPrefs.setWifiDiscoveryAsked(this) - wifiLocationPermission.launch(WifiDiscovery.permissions) - } - }, - onWifiDiscoverySettings = { openWifiDiscoverySettings() }, + onIntegration = ::configureIntegration, + onIntegrationAppInfo = ::openAppInfo, + onIntegrationLocation = ::openWifiDiscoverySettings, onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value }, onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on }, onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) }, diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 8172ccc59b..501024b968 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -788,6 +788,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) { if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) { backQamInput.cancel() + com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this@SessionActivity) cancelTouchGestures() screenKeys?.stopEditing() } @@ -2127,6 +2128,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } private fun releasePads() { + com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this) backQamInput.cancel() padBridge?.releaseAll() joyConVr?.releaseButtons() @@ -3277,6 +3279,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onScreenControls?.reload() controllerSettings = ControllerPrefs.read(this) resumed = true + com.droiddeck.launcher.input.HomeButtonShortcuts.attach(this, + enabled = { + resumed && window.decorView.hasWindowFocus() && !ended && !drawerOpen && !pcKeyboardOpen && + !achievementsOpen && !gestureSettingsOpen && !pipUi && SessionState.running && !SessionState.suspended && + SessionState.mode == SessionService.MODE_STEAM && padBridge?.canHoldGuide() == true + }, + setPressed = { padBridge?.setHomeGuidePressed(it) }, + onCancel = { padBridge?.cancelHomeGuide() }, + ) updatePointerCapture() if (!pipUi) sessionClipboard.start() updatePadMotion() @@ -3288,6 +3299,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } override fun onPause() { + com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this) if (runtimeRemovalBlocked) { super.onPause(); return } backQamInput.cancel() capturePausedFrame() @@ -3673,6 +3685,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) + if (!hasFocus) com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this) if (!hasFocus) backQamInput.cancel() if (!hasFocus && ::padMouse.isInitialized) padMouse.reset() if (runtimeRemovalBlocked) return @@ -3721,6 +3734,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } override fun onDestroy() { + com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this) backQamInput.cancel() steamVrRecovery.close() uiHandler.removeCallbacks(steamTouchRetry) diff --git a/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt b/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt new file mode 100644 index 0000000000..982b609474 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt @@ -0,0 +1,72 @@ +package com.droiddeck.launcher.core + +import android.accessibilityservice.AccessibilityServiceInfo +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.provider.Settings +import android.view.accessibility.AccessibilityManager +import com.droiddeck.launcher.HomeApp +import com.droiddeck.launcher.input.HomeButtonService +import com.droiddeck.launcher.session.SessionPrefs + +object SteamIntegration { + const val ACTION_SETUP = "com.droiddeck.launcher.STEAM_INTEGRATION" + const val EXTRA_FEATURE = "integration_feature" + enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS } + + data class State( + val wifi: Boolean = false, + val locationPermission: Boolean = false, + val locationOn: Boolean = false, + val locationBlocked: Boolean = false, + val brightness: Boolean = false, + val home: Boolean = false, + val shortcuts: Boolean = false, + val shortcutsRestricted: Boolean = false, + val shortcutsTried: Boolean = false, + val suggested: Boolean = true, + ) + + fun read(context: Context) = State( + wifi = SessionPrefs.wifiDiscoveryEnabled(context), + locationPermission = WifiDiscovery.permissionGranted(context), + locationOn = WifiDiscovery.locationEnabled(context), + brightness = Settings.System.canWrite(context), + home = HomeApp.isDefault(context), + shortcuts = context.getSystemService(AccessibilityManager::class.java) + .getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK).any { + val service = it.resolveInfo.serviceInfo + ComponentName(service.packageName, service.name) == ComponentName(context, HomeButtonService::class.java) + }, + shortcutsRestricted = restrictedSettings(context), + suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false), + ) + + // Android 13+ blocks accessibility services for sideloaded APKs until the user allows restricted settings in App info. + // MODE_DEFAULT is inconclusive on Android 15, so only an explicit denial counts here. + private fun restrictedSettings(context: Context): Boolean { + if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false + val mode = runCatching { + context.getSystemService(android.app.AppOpsManager::class.java) + .unsafeCheckOpNoThrow("android:access_restricted_settings", android.os.Process.myUid(), context.packageName) + }.getOrDefault(android.app.AppOpsManager.MODE_ALLOWED) + return mode == android.app.AppOpsManager.MODE_ERRORED || mode == android.app.AppOpsManager.MODE_IGNORED + } + + fun dismissSuggestion(context: Context) { + SessionPrefs.sessionPrefs(context).edit().putBoolean("steam_integration_seen", true).apply() + } + + fun brightnessSettings(context: Context) = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, + Uri.parse("package:${context.packageName}")) + + // ACCESSIBILITY_DETAILS_SETTINGS is restricted to system apps; the fragment args key highlights our entry in the list. + fun shortcutSettings(context: Context): Intent { + val service = ComponentName(context, HomeButtonService::class.java).flattenToString() + return Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS) + .putExtra(":settings:fragment_args_key", service) + .putExtra(":settings:show_fragment_args", android.os.Bundle().apply { putString(":settings:fragment_args_key", service) }) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/HomeButtonService.kt b/app/src/main/java/com/droiddeck/launcher/input/HomeButtonService.kt new file mode 100644 index 0000000000..f7d918bdf5 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/HomeButtonService.kt @@ -0,0 +1,70 @@ +package com.droiddeck.launcher.input + +import android.accessibilityservice.AccessibilityService +import android.content.Context +import android.content.Intent +import android.hardware.input.InputManager +import android.os.Handler +import android.os.Looper +import android.view.KeyEvent +import android.view.accessibility.AccessibilityEvent +import com.droiddeck.launcher.HomeApp + +object HomeButtonShortcuts { + private var owner: Any? = null + private var enabled: () -> Boolean = { false } + private var setPressed: (Boolean) -> Unit = {} + private var onCancel: () -> Unit = {} + private val input = HomeGuideInput({ setPressed(it) }, { onCancel() }) + + fun attach(owner: Any, enabled: () -> Boolean, setPressed: (Boolean) -> Unit, onCancel: () -> Unit) { + input.cancel() + this.owner = owner + this.enabled = enabled + this.setPressed = setPressed + this.onCancel = onCancel + } + + fun cancel(owner: Any) { if (this.owner === owner) input.cancel() } + + fun detach(owner: Any) { + if (this.owner !== owner) return + input.cancel() + this.owner = null + enabled = { false } + setPressed = {} + onCancel = {} + } + + fun onKeyEvent(context: Context, event: KeyEvent): Boolean { + if (event.keyCode != KeyEvent.KEYCODE_HOME) return false + return input.onKeyEvent(event, enabled() && HomeApp.isDefault(context)) + } + + fun release() = input.cancel() + fun onDeviceRemoved(device: Int) = input.onDeviceRemoved(device) +} + +class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListener { + override fun onServiceConnected() { + getSystemService(InputManager::class.java).registerInputDeviceListener(this, Handler(Looper.getMainLooper())) + } + + override fun onKeyEvent(event: KeyEvent) = HomeButtonShortcuts.onKeyEvent(this, event) + override fun onAccessibilityEvent(event: AccessibilityEvent?) {} + override fun onInterrupt() { HomeButtonShortcuts.release() } + override fun onInputDeviceAdded(deviceId: Int) {} + override fun onInputDeviceChanged(deviceId: Int) {} + override fun onInputDeviceRemoved(deviceId: Int) { HomeButtonShortcuts.onDeviceRemoved(deviceId) } + + override fun onUnbind(intent: Intent?): Boolean { + HomeButtonShortcuts.release() + return super.onUnbind(intent) + } + + override fun onDestroy() { + HomeButtonShortcuts.release() + getSystemService(InputManager::class.java).unregisterInputDeviceListener(this) + super.onDestroy() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/HomeGuideInput.kt b/app/src/main/java/com/droiddeck/launcher/input/HomeGuideInput.kt new file mode 100644 index 0000000000..dfb7dbb0a1 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/HomeGuideInput.kt @@ -0,0 +1,42 @@ +package com.droiddeck.launcher.input + +import android.view.KeyEvent + +class HomeGuideInput(private val setPressed: (Boolean) -> Unit, private val onCancel: () -> Unit = {}) { + private val presses = mutableSetOf() + private val cancelled = mutableSetOf() + + fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean { + if (event.keyCode != KeyEvent.KEYCODE_HOME) return false + if (!enabled) cancel() + val device = event.deviceId + return when (event.action) { + KeyEvent.ACTION_DOWN -> { + if (event.repeatCount > 0) return device in presses || device in cancelled + cancelled.remove(device) + if (!enabled || event.isCanceled) return false + if (presses.add(device) && presses.size == 1) setPressed(true) + true + } + KeyEvent.ACTION_UP -> { + val owned = presses.remove(device) + val wasCancelled = cancelled.remove(device) + if (owned && presses.isEmpty()) setPressed(false) + owned || wasCancelled + } + else -> device in presses || device in cancelled + } + } + + fun cancel() { + val held = presses.isNotEmpty() + cancelled.addAll(presses) + presses.clear() + if (held) { onCancel(); setPressed(false) } + } + + fun onDeviceRemoved(device: Int) { + cancelled.remove(device) + if (presses.remove(device) && presses.isEmpty()) { onCancel(); setPressed(false) } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java index 3d27da5547..28ee6403f0 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java +++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java @@ -62,6 +62,7 @@ public final class PadBridge { private boolean systemGuidePressed; private boolean systemQamPressed; private boolean backQamPressed; + private boolean homeGuidePressed; private final PadState lastBackQamReport = new PadState(); private final PadState lastWrittenReport = new PadState(); private boolean backQamAxesBlocked; @@ -136,6 +137,7 @@ public final class PadBridge { } private void resetBuiltin() { + homeGuidePressed = false; clearBackQamWrites(); routedTouch.clear(); systemGuidePressed = false; @@ -159,6 +161,7 @@ public final class PadBridge { } public synchronized void stop() { + homeGuidePressed = false; clearBackQamWrites(); releaseBackPaddles(); activeControllerId = NO_CONTROLLER; @@ -481,6 +484,7 @@ public final class PadBridge { } public synchronized void releaseAll() { + homeGuidePressed = false; clearBackQamWrites(); routedTouch.clear(); backQamPressed = false; @@ -508,10 +512,33 @@ public final class PadBridge { return builtinPad && nativeQam(); } + public boolean canHoldGuide() { + return builtinPad; + } + + public synchronized void setHomeGuidePressed(boolean pressed) { + if (pressed && !canHoldGuide()) return; + if (homeGuidePressed == pressed) return; + homeGuidePressed = pressed; + updateHeldModifier(PadState.GUIDE, pressed); + } + + public synchronized void cancelHomeGuide() { + if (!homeGuidePressed) return; + clearBackQamWrites(); + homeGuidePressed = false; + state.clear(); + publish(); + } + public synchronized void setBackQamPressed(boolean pressed) { if (pressed && !canHoldQam()) return; if (backQamPressed == pressed) return; backQamPressed = pressed; + updateHeldModifier(PadState.QAM, pressed); + } + + private void updateHeldModifier(int button, boolean pressed) { if (pressed && (open || start())) { backQamAxesBlocked = false; long now = android.os.SystemClock.uptimeMillis(); @@ -519,10 +546,10 @@ public final class PadBridge { backQamDelayMs = modifierAt - now + QAM_GUIDE_LEAD_MIN_MS; PadState modifier = new PadState(); modifier.copyFrom(lastBackQamReport); - modifier.press(PadState.QAM, true); + modifier.press(button, true); writeBackQamReport(modifier, modifierAt); } - if (!pressed) { + if (!pressed && !backQamPressed && !homeGuidePressed) { backQamAxesBlocked = hasAxes(state); if (!backQamWrites.isEmpty()) { PadState neutral = new PadState(); @@ -578,7 +605,7 @@ public final class PadBridge { if (backQamAxesBlocked && !hasAxes(state)) backQamAxesBlocked = false; long at = android.os.SystemClock.uptimeMillis(); // Steam must see the modifier before a partner; preserve quick press/release pairs in order. - if (backQamPressed || !backQamWrites.isEmpty()) at += backQamDelayMs; + if (backQamPressed || homeGuidePressed || !backQamWrites.isEmpty()) at += backQamDelayMs; writeBackQamReport(report, at); } @@ -609,7 +636,8 @@ public final class PadBridge { live.rightX = state.rightX; live.rightY = state.rightY; live.leftTrigger = state.leftTrigger; live.rightTrigger = state.rightTrigger; } - if ((queued && (!backQamPressed || !report.isDown(PadState.QAM))) || backQamAxesBlocked) clearAxes(live); + boolean held = (backQamPressed && report.isDown(PadState.QAM)) || (homeGuidePressed && report.isDown(PadState.GUIDE)); + if ((queued && !held) || backQamAxesBlocked) clearAxes(live); lastWrittenReport.copyFrom(live); writer.writePad(live); } @@ -821,7 +849,7 @@ public final class PadBridge { statDropped++; return; } - boolean guide = systemGuidePressed || qamChordActive; + boolean guide = systemGuidePressed || qamChordActive || homeGuidePressed; boolean qam = nativeQam() && (systemQamPressed || qamTapPressed || backQamPressed); if (!guide && !qam) { writePad(state); diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt index 3e0eaf8b21..f5780da94f 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt @@ -8,11 +8,9 @@ import android.app.NotificationManager import android.app.PendingIntent import android.database.ContentObserver import android.media.AudioManager -import android.net.Uri import android.os.FileObserver import android.os.Handler import android.os.Looper -import android.os.SystemClock import android.provider.Settings import android.util.Log import com.droiddeck.launcher.core.SessionPart @@ -29,8 +27,7 @@ class DeviceControlsComponent(context: Context, root: File, private val activity private val directory = directory(root) private val handler = Handler(Looper.getMainLooper()) private var running = false - private var pendingBrightness: Float? = null - private var permissionRequestAt = -5_000L + private var permissionNotified = false private var previous = "" private var revision = 0L init { prepareBacklight(context, root) } @@ -46,13 +43,8 @@ class DeviceControlsComponent(context: Context, root: File, private val activity override fun run() { if (!running) return consume() - pendingBrightness?.let { value -> - if (Settings.System.canWrite(context)) { - pendingBrightness = null - context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION) - brightness(value) - } - } + if (permissionNotified && Settings.System.canWrite(context)) + context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION) publish() handler.postDelayed(this, 250) } @@ -86,6 +78,7 @@ class DeviceControlsComponent(context: Context, root: File, private val activity File(directory, "$it.processing").delete() } running = true + permissionNotified = false context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, observer) requests.startWatching() refresh.run() @@ -98,7 +91,6 @@ class DeviceControlsComponent(context: Context, root: File, private val activity handler.removeCallbacks(refresh) requests.stopWatching() context.contentResolver.unregisterContentObserver(observer) - pendingBrightness = null context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION) } } @@ -134,13 +126,13 @@ class DeviceControlsComponent(context: Context, root: File, private val activity private fun brightness(value: Float) { if (!Settings.System.canWrite(context)) { - pendingBrightness = value - val now = SystemClock.elapsedRealtime() - if (now - permissionRequestAt >= 5_000) { - permissionRequestAt = now + if (!permissionNotified) { + permissionNotified = true try { - val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, - Uri.parse("package:${context.packageName}")).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + val intent = Intent(context, com.droiddeck.launcher.FrontEndActivity::class.java) + .setAction(com.droiddeck.launcher.core.SteamIntegration.ACTION_SETUP) + .putExtra(com.droiddeck.launcher.core.SteamIntegration.EXTRA_FEATURE, "BRIGHTNESS") + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) val manager = context.getSystemService(NotificationManager::class.java) manager.createNotificationChannel(NotificationChannel(PERMISSION_CHANNEL, context.getString(R.string.brightness_permission_title), NotificationManager.IMPORTANCE_DEFAULT)) @@ -150,7 +142,8 @@ class DeviceControlsComponent(context: Context, root: File, private val activity .setContentTitle(context.getString(R.string.brightness_permission_title)) .setContentText(context.getString(R.string.brightness_permission_text)) .setContentIntent(action).setOnlyAlertOnce(true).setAutoCancel(true).build()) - if (activityVisible()) context.startActivity(intent) + if (activityVisible()) android.widget.Toast.makeText(context, R.string.integration_brightness_needed, + android.widget.Toast.LENGTH_LONG).show() } catch (e: Exception) { Log.w(TAG, "Could not open brightness permission", e) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index 4df261e8d2..e75994776a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -121,6 +121,8 @@ class FrontEndState( val isHomeApp: Boolean = false, val homeScreenEnabled: Boolean = false, val defaultHomeLabel: String? = null, + val integration: com.droiddeck.launcher.core.SteamIntegration.State = com.droiddeck.launcher.core.SteamIntegration.State(suggested = false), + val integrationFocus: com.droiddeck.launcher.core.SteamIntegration.Feature? = null, val androidApps: List = emptyList(), val secondScreenDisplays: List = emptyList(), val packages: List? = null, @@ -237,6 +239,11 @@ class FrontEndActions( val onLibraryChanged: () -> Unit = {}, val onHomeApp: () -> Unit = {}, val onHomeScreen: (Boolean) -> Unit = {}, + val onSteamIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature?) -> Unit = {}, + val onDismissIntegration: () -> Unit = {}, + val onIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature) -> Unit = {}, + val onIntegrationAppInfo: () -> Unit = {}, + val onIntegrationLocation: () -> Unit = {}, val onAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit = { _, _ -> }, val onBackActionsInverted: (Boolean) -> Unit = {}, val onRefreshPhantomStatus: () -> Unit = {}, @@ -408,6 +415,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com "stores:downloads" -> { com.droiddeck.launcher.stores.StoresState.openDownloads = true; selected = "stores" } "components" -> a.onComponents(true) "setup:launcher" -> { SetupTabs.openLauncher = true; selected = "setup" } + "setup:integration" -> { SetupTabs.openOverview = true; selected = "setup" } else -> selected = target } a.onNavigated() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index 43926aa6b1..d5932762f7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -91,6 +91,7 @@ private const val LAUNCHER_TAB = 2 internal object SetupTabs { var openLauncher = false + var openOverview = false } private const val GLASSES_TAB = 5 @@ -191,6 +192,7 @@ internal fun SetupPanel( val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_launcher), stringResource(R.string.setup_tab_storage), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses)) var tab by rememberSaveable { mutableStateOf(if (SetupTabs.openLauncher) LAUNCHER_TAB else 0) } SetupTabs.openLauncher = false + if (SetupTabs.openOverview) { tab = 0; SetupTabs.openOverview = false } val chipFocus = remember { List(tabs.size) { FocusRequester() } } var tabTurned by remember { mutableStateOf(false) } val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true } @@ -341,6 +343,7 @@ internal fun SetupPanel( } } SettingsGroup(stringResource(R.string.setup_runtime)) { runtimeCheck(false) } + SteamIntegrationGroup(s.integration, s.integrationFocus, a.onIntegration, a.onIntegrationAppInfo, a.onIntegrationLocation) } 1 -> { val controller = s.controller 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 f8f8857645..1e07f6c47f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -96,11 +96,7 @@ class ModeSettings( val bootMovieCustomName: String? = null, val bootMovieImporting: Boolean = false, val bootMovieProgress: Int = -1, - val wifiDiscovery: Boolean? = null, - val wifiDiscoveryPermission: Boolean = false, - val wifiDiscoveryLocation: Boolean = false, - val wifiDiscoveryAsked: Boolean = false, - val wifiDiscoveryBlocked: Boolean = false, + val integration: com.droiddeck.launcher.core.SteamIntegration.State? = null, val deckyInstalled: String? = null, val deckyLatestRelease: DeckyManager.Release? = null, val deckyBranch: Int = DeckyManager.BRANCH_STABLE, @@ -148,8 +144,9 @@ class ModeSettingsActions( val onBootMovieSound: (Boolean) -> Unit = {}, val onImportBootMovie: () -> Unit = {}, val onBootMovieChanged: () -> Unit = {}, - val onWifiDiscovery: (Boolean) -> Unit = {}, - val onWifiDiscoverySettings: () -> Unit = {}, + val onIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature) -> Unit = {}, + val onIntegrationAppInfo: () -> Unit = {}, + val onIntegrationLocation: () -> Unit = {}, val onDeckyInstall: (DeckyManager.Release) -> Unit = {}, val onDeckyCheck: () -> Unit = {}, val onDeckyBranch: (Int) -> Unit = {}, @@ -208,7 +205,6 @@ class SheetExtras( fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: SheetExtras = SheetExtras()) { val steam = s.mode == SessionService.MODE_STEAM val host = rememberMenuHost() - var explainWifiDiscovery by remember { mutableStateOf(false) } if (tab == SheetTab.DISPLAY) { val context = LocalContext.current val portraitWindow = SessionPrefs.portrait(context) @@ -512,39 +508,9 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: ) } if (s.bootMovie != null) BootMovieGroup(s, a, host) - if (s.wifiDiscovery != null) SettingsGroup(stringResource(R.string.mode_network)) { - val hint = when { - s.wifiDiscovery && !s.wifiDiscoveryLocation -> stringResource(R.string.mode_wifi_location_off) - !s.wifiDiscoveryPermission && s.wifiDiscoveryAsked -> stringResource(R.string.mode_wifi_permission_denied) - else -> stringResource(R.string.mode_wifi_discovery_hint) - } - SettingsRow(stringResource(R.string.mode_wifi_discovery), hint) { - Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically, - horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp)) { - if (s.wifiDiscoveryBlocked || (s.wifiDiscovery && !s.wifiDiscoveryLocation)) { - SecondaryButton(stringResource(R.string.mode_wifi_open_settings), onClick = a.onWifiDiscoverySettings) - } - ToggleSwitch(s.wifiDiscovery, label = stringResource(R.string.mode_wifi_discovery)) { on -> - host.open = null - if (on) explainWifiDiscovery = true else a.onWifiDiscovery(false) - } - } - } - } + if (s.integration != null) SteamIntegrationGroup(s.integration, + onFeature = a.onIntegration, onAppInfo = a.onIntegrationAppInfo, onLocation = a.onIntegrationLocation) } - if (explainWifiDiscovery) AlertDialog( - onDismissRequest = { explainWifiDiscovery = false }, - title = { Text(stringResource(R.string.mode_wifi_explain_title)) }, - text = { Text(stringResource(R.string.mode_wifi_explain_text)) }, - confirmButton = { - TextButton(onClick = { explainWifiDiscovery = false; a.onWifiDiscovery(true) }, modifier = Modifier.focusGlide(CircleShape)) { - Text(stringResource(if (s.wifiDiscoveryBlocked) R.string.mode_wifi_open_settings else R.string.mode_wifi_continue)) - } - }, - dismissButton = { - TextButton(onClick = { explainWifiDiscovery = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } - }, - ) } @Composable diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index f4c1837888..6725ac3193 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -422,7 +422,7 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo } @Composable -fun SettingsGroup(title: String, compact: Boolean = false, content: @Composable ColumnScope.() -> Unit) { +fun SettingsGroup(title: String, compact: Boolean = false, detail: String? = null, content: @Composable ColumnScope.() -> Unit) { val tight = compact || LocalCompactSettings.current val colors = MaterialTheme.colorScheme val pal = LocalPalette.current @@ -434,6 +434,7 @@ fun SettingsGroup(title: String, compact: Boolean = false, content: @Composable ) { Text(title.uppercase(), fontSize = if (tight) 11.sp else 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant) Box(modifier = Modifier.weight(1f).height(1.dp).background(pal.line)) + if (detail != null) Text(detail, fontSize = if (tight) 11.sp else 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant) } Column(modifier = Modifier.fillMaxWidth().clip(GroupShape).background(colors.surface).border(1.dp, pal.line, GroupShape)) { content() } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt index 49cfd2da49..4a93056dda 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt @@ -143,6 +143,8 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) words = { val runtimeStatus: @Composable () -> Unit = { if (s.busy || !s.ready || (s.available != null && s.available != s.installed)) RuntimeChip(s) + else if (s.integration.suggested && signedIn && !com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)) + IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration) } if (narrow) Column( verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.onPlaced { words = it.boundsInParent() }, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt new file mode 100644 index 0000000000..d7f030695d --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt @@ -0,0 +1,215 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.animation.animateColorAsState +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.AutoAwesome +import androidx.compose.material.icons.outlined.Close +import androidx.compose.material.icons.outlined.Home +import androidx.compose.material.icons.outlined.KeyboardCommandKey +import androidx.compose.material.icons.outlined.LightMode +import androidx.compose.material.icons.outlined.Wifi +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.core.SteamIntegration +import com.droiddeck.launcher.core.SteamIntegration.Feature + +private val BadgeShape = RoundedCornerShape(10.dp) + +internal fun SteamIntegration.State.enabled(feature: Feature) = when (feature) { + Feature.WIFI -> wifi && locationPermission && locationOn + Feature.BRIGHTNESS -> brightness + Feature.HOME -> home + Feature.SHORTCUTS -> home && shortcuts +} + +internal fun SteamIntegration.State.enabledCount() = Feature.entries.count { enabled(it) } + +@Composable +internal fun SteamIntegrationGroup( + state: SteamIntegration.State, + focus: Feature? = null, + onFeature: (Feature) -> Unit, + onAppInfo: () -> Unit, + onLocation: () -> Unit = {}, +) { + SettingsGroup( + stringResource(R.string.integration_title), + detail = stringResource(R.string.integration_count, state.enabledCount(), Feature.entries.size), + ) { + Feature.entries.forEachIndexed { i, feature -> + IntegrationRow(state, feature, focus == feature, i < Feature.entries.lastIndex, onFeature, onAppInfo, onLocation) + } + } +} + +@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) +@Composable +private fun IntegrationRow( + state: SteamIntegration.State, + feature: Feature, + focused: Boolean, + divider: Boolean, + onFeature: (Feature) -> Unit, + onAppInfo: () -> Unit, + onLocation: () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val on = state.enabled(feature) + var flash by remember { mutableStateOf(false) } + val reveal = remember { BringIntoViewRequester() } + LaunchedEffect(focused) { + if (focused) try { flash = true; reveal.bringIntoView(); kotlinx.coroutines.delay(1600) } finally { flash = false } + } + val bg by animateColorAsState(if (flash) pal.signal.copy(alpha = 0.12f) else Color.Transparent, Motion.tw(400), label = "integrationFlash") + val wifiLocationOff = feature == Feature.WIFI && state.wifi && state.locationPermission && !state.locationOn + val wifiDenied = feature == Feature.WIFI && !state.locationPermission && state.locationBlocked + val needsHome = feature == Feature.SHORTCUTS && !state.home + val restricted = feature == Feature.SHORTCUTS && !needsHome && !state.shortcuts && state.shortcutsRestricted + val maybeRestricted = feature == Feature.SHORTCUTS && !needsHome && !state.shortcuts && !restricted && state.shortcutsTried && + android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU + val hint = stringResource(when { + wifiLocationOff -> R.string.integration_wifi_location_off + wifiDenied -> R.string.integration_wifi_denied + needsHome -> R.string.integration_shortcuts_needs_home + restricted -> R.string.integration_shortcuts_restricted + maybeRestricted -> R.string.integration_shortcuts_maybe_restricted + feature == Feature.WIFI -> if (on) R.string.integration_wifi_on else R.string.integration_wifi_hint + feature == Feature.BRIGHTNESS -> R.string.integration_brightness_hint + feature == Feature.HOME -> R.string.integration_home_hint + else -> R.string.integration_shortcuts_hint + }) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(14.dp), + modifier = Modifier.fillMaxWidth().bringIntoViewRequester(reveal).background(bg).heightIn(min = 64.dp) + .padding(horizontal = 14.dp, vertical = 10.dp) + .testTag("integration-${feature.name.lowercase()}"), + ) { + FeatureBadge(featureIcon(feature), on) + Column(Modifier.weight(1f)) { + Text(stringResource(featureTitle(feature)), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, + maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(hint, fontSize = 13.sp, color = if (wifiLocationOff || wifiDenied || restricted) AttentionAmber else colors.onSurfaceVariant, + maxLines = 1, overflow = TextOverflow.Ellipsis) + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + when { + wifiLocationOff -> SecondaryButton(stringResource(R.string.integration_location), compact = true, onClick = onLocation) + wifiDenied -> SecondaryButton(stringResource(R.string.integration_app_info), compact = true, onClick = onLocation) + restricted || maybeRestricted -> SecondaryButton(stringResource(R.string.integration_app_info), compact = true, onClick = onAppInfo) + } + val checked = if (feature == Feature.WIFI) state.wifi && state.locationPermission else on + ToggleSwitch(checked, enabled = !needsHome && !restricted, label = stringResource(featureTitle(feature)), + modifier = Modifier.testTag("integration-action-${feature.name.lowercase()}")) { onFeature(feature) } + } + } + if (divider) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) +} + +@Composable +private fun FeatureBadge(icon: ImageVector, on: Boolean) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val tint by animateColorAsState(if (on) pal.good else colors.onSurfaceVariant, Motion.tw(250), label = "badgeTint") + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.size(36.dp).clip(BadgeShape) + .background(if (on) pal.good.copy(alpha = 0.14f) else colors.surfaceVariant) + .border(1.dp, if (on) pal.good.copy(alpha = 0.3f) else pal.line2, BadgeShape), + ) { Icon(icon, contentDescription = null, tint = tint, modifier = Modifier.size(19.dp)) } +} + +private fun featureIcon(feature: Feature) = when (feature) { + Feature.WIFI -> Icons.Outlined.Wifi + Feature.BRIGHTNESS -> Icons.Outlined.LightMode + Feature.HOME -> Icons.Outlined.Home + Feature.SHORTCUTS -> Icons.Outlined.KeyboardCommandKey +} + +private fun featureTitle(feature: Feature) = when (feature) { + Feature.WIFI -> R.string.integration_wifi + Feature.BRIGHTNESS -> R.string.integration_brightness + Feature.HOME -> R.string.integration_home + Feature.SHORTCUTS -> R.string.integration_shortcuts +} + +@Composable +internal fun IntegrationSuggestion(state: SteamIntegration.State, onOpen: () -> Unit, onLater: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val pill = RoundedCornerShape(99.dp) + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.clip(pill).background(colors.surfaceVariant.copy(alpha = 0.85f)) + .border(1.dp, pal.signal.copy(alpha = 0.3f), pill).testTag("integration-suggestion"), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.heightIn(min = 40.dp).clip(pill).glideBorder(hot, pill, pal.signal, Color.Transparent) + .hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onOpen) + .controllerConfirm(onClick = onOpen) + .padding(start = 12.dp, end = 10.dp, top = 6.dp, bottom = 6.dp), + ) { + Icon(Icons.Outlined.AutoAwesome, contentDescription = null, tint = pal.signal, modifier = Modifier.size(16.dp)) + Text(stringResource(R.string.integration_title), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1) + Text(stringResource(R.string.integration_count, state.enabledCount(), Feature.entries.size), fontSize = 12.sp, + color = colors.onSurfaceVariant, maxLines = 1) + } + val closeSrc = remember { MutableInteractionSource() } + val closeHot = rememberHot(closeSrc) + val later = stringResource(R.string.integration_later) + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.padding(end = 4.dp).size(32.dp).clip(CircleShape) + .background(if (closeHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent) + .glideBorder(closeHot, CircleShape, pal.signal, Color.Transparent) + .hoverable(closeSrc).clickable(role = Role.Button, interactionSource = closeSrc, indication = LocalIndication.current, onClick = onLater) + .controllerConfirm(onClick = onLater) + .semantics { contentDescription = later }, + ) { Icon(Icons.Outlined.Close, contentDescription = null, tint = colors.onSurfaceVariant, modifier = Modifier.size(16.dp)) } + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 89991465b5..d826e83df7 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -310,7 +310,7 @@ Double-tap window %1$d ms Allow brightness control - Tap to allow Steam to change Android screen brightness. + Set up brightness control in DroidDeck. Menu → QAM QAM → Menu Session @@ -3240,4 +3240,27 @@ Cloud settings Xbox Cloud Gaming Game Pass + Steam integration + %1$d of %2$d on + Set up + Not now + Location + App info + Wi-Fi names + Brightness + DroidDeck as Home + Home button shortcuts + Show networks in Steam · needs Location access, never tracked + Networks show in Steam + Location is off + Location denied · allow it in App info + Steam’s slider sets screen brightness + Home opens the Steam menu in a session + Hold Home for Steam Guide chords + Needs DroidDeck as Home + Greyed out in Android? App info → ⋮ → Allow restricted settings + Blocked by Android · App info → ⋮ → Allow restricted settings + DroidDeck Home button + Pass Home button presses to Steam Guide while a Steam session is focused and DroidDeck is the default Home app. Does not read screen content. + Turn on Brightness in Setup → Steam integration diff --git a/app/src/main/res/xml/home_button_service.xml b/app/src/main/res/xml/home_button_service.xml new file mode 100644 index 0000000000..3b094dcd54 --- /dev/null +++ b/app/src/main/res/xml/home_button_service.xml @@ -0,0 +1,7 @@ + + diff --git a/app/src/test/java/com/droiddeck/launcher/input/HomeGuideInputTest.kt b/app/src/test/java/com/droiddeck/launcher/input/HomeGuideInputTest.kt new file mode 100644 index 0000000000..ccef31215d --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/HomeGuideInputTest.kt @@ -0,0 +1,62 @@ +package com.droiddeck.launcher.input + +import android.app.Application +import android.view.KeyEvent +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28, 33], manifest = Config.NONE, application = Application::class) +class HomeGuideInputTest { + private val states = mutableListOf() + private var cancellations = 0 + private val input = HomeGuideInput({ states.add(it) }, { cancellations++ }) + + private fun home(action: Int, device: Int = 10, repeat: Int = 0, down: Long = 10) = + KeyEvent(down, down + 100, action, KeyEvent.KEYCODE_HOME, repeat, 0, device, 102) + + @Test fun guideIsHeldImmediatelyAndReleaseDoesNotDependOnAndroidDownTime() { + assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_DOWN), true)) + assertEquals(listOf(true), states) + assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_DOWN, repeat = 1), true)) + assertFalse(input.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_X), true)) + assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_UP, down = 77), true)) + assertEquals(listOf(true, false), states) + } + + @Test fun anUnownedHomePressKeepsAndroidBehaviorEvenIfSessionBecomesEligibleBeforeRelease() { + assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_DOWN), false)) + assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_UP), true)) + assertTrue(states.isEmpty()) + } + + @Test fun focusLossReleasesGuideAndConsumesTheOwnedReleaseWithoutAnotherTap() { + input.onKeyEvent(home(KeyEvent.ACTION_DOWN), true) + input.cancel() + assertEquals(1, cancellations) + assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_DOWN, repeat = 2), false)) + assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_UP), false)) + assertEquals(listOf(true, false), states) + assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_UP), false)) + } + + @Test fun disablingDuringAHoldReleasesItAndDoesNotStealTheNextAndroidHomePress() { + input.onKeyEvent(home(KeyEvent.ACTION_DOWN), true) + assertTrue(input.onKeyEvent(home(KeyEvent.ACTION_UP), false)) + assertEquals(listOf(true, false), states) + assertFalse(input.onKeyEvent(home(KeyEvent.ACTION_DOWN), false)) + } + + @Test fun guideStaysHeldUntilAllOwnersReleaseAndDisconnectCancelsTheLastOwner() { + input.onKeyEvent(home(KeyEvent.ACTION_DOWN), true) + input.onKeyEvent(home(KeyEvent.ACTION_DOWN, device = 11), true) + input.onKeyEvent(home(KeyEvent.ACTION_UP), true) + assertEquals(listOf(true), states) + input.onDeviceRemoved(11) + assertEquals(listOf(true, false), states) + assertEquals(1, cancellations) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt index 78a790892f..9ac6ecfccd 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt @@ -328,6 +328,53 @@ class PadBridgeQamTest { } } + @Test fun homeGuidePrecedesEarlyPartnerInputAndDoesNotGenerateABareButton() { + bridge.setHomeGuidePressed(true) + assertTrue(pad().isDown(PadState.GUIDE)) + bridge.applyExternal({ it.press(PadState.X, true) }, true) + assertFalse(pad().isDown(PadState.X)) + advance(80) + assertTrue(pad().isDown(PadState.GUIDE)) + assertTrue(pad().isDown(PadState.X)) + bridge.applyExternal({ it.press(PadState.X, false) }, true) + bridge.setHomeGuidePressed(false) + advance(1000) + assertFalse(pad().isDown(PadState.GUIDE)) + assertFalse(pad().isDown(PadState.X)) + } + + @Test fun cancellingHomeDiscardsQueuedPartnersAndReleasesGuideImmediately() { + bridge.setHomeGuidePressed(true) + bridge.applyExternal({ it.press(PadState.LB, true); it.leftY = -1f }, true) + bridge.cancelHomeGuide() + advance(1000) + assertFalse(pad().isDown(PadState.GUIDE)) + assertFalse(pad().isDown(PadState.LB)) + assertEquals(0f, pad().leftY) + } + + @Test fun homeAndTouchGuideHaveIndependentReleases() { + bridge.setHomeGuidePressed(true) + bridge.setSystemButtons(true, false) + bridge.setHomeGuidePressed(false) + advance(1000) + assertTrue(pad().isDown(PadState.GUIDE)) + bridge.setSystemButtons(false, false) + advance(1000) + assertFalse(pad().isDown(PadState.GUIDE)) + } + + @Test fun releasingHomeStopsHeldAxesFromBecomingNavigation() { + bridge.setHomeGuidePressed(true) + bridge.applyExternal({ it.leftY = -1f }, true) + advance(80) + assertEquals(-1f, pad().leftY) + bridge.setHomeGuidePressed(false) + advance(1000) + assertEquals(0f, pad().leftY) + assertFalse(pad().isDown(PadState.GUIDE)) + } + private fun key(device: InputDevice, code: Int, action: Int = KeyEvent.ACTION_DOWN, repeat: Int = 0, scan: Int = 0) = KeyEvent(0L, 0L, action, code, repeat, 0, device.id, scan, 0, InputDevice.SOURCE_GAMEPAD) diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt index fa96dacc99..db035a656a 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt @@ -66,14 +66,16 @@ class DeviceControlsComponentTest { assertEquals(3, audio.getStreamVolume(AudioManager.STREAM_MUSIC)) } - @Test fun deniedBrightnessIsReadBackAndAppliedOnlyAfterPermission() { + @Test fun deniedBrightnessDoesNotOpenSettingsOrReplayAnOldSliderValueAfterPermission() { WriteSettingsShadow.writable = false request("brightness", "0.75") assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) - assertEquals(Settings.ACTION_MANAGE_WRITE_SETTINGS, shadowOf(context).nextStartedActivity.action) + assertNull(shadowOf(context).nextStartedActivity) assertFalse(JSONObject(File(directory, "state.json").readText()).getBoolean("brightnessWritable")) WriteSettingsShadow.writable = true tick() + assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + request("brightness", "0.75") assertEquals(192, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) } @@ -87,7 +89,7 @@ class DeviceControlsComponentTest { assertEquals(1.0, JSONObject(File(directory, "state.json").readText()).getDouble("brightness"), 0.0001) } - @Test fun hiddenPermissionRequestOffersANotificationAndRetainsTheLatestValue() { + @Test fun permissionNotificationOpensOptionalLauncherSetupOnlyWhenSelected() { visible = false WriteSettingsShadow.writable = false request("brightness", "0.25") @@ -96,11 +98,13 @@ class DeviceControlsComponentTest { val notifications = context.getSystemService(NotificationManager::class.java) val notification = notifications.activeNotifications.single().notification notification.contentIntent.send() - assertEquals(Settings.ACTION_MANAGE_WRITE_SETTINGS, shadowOf(context).nextStartedActivity.action) + val intent = shadowOf(context).nextStartedActivity + assertEquals(com.droiddeck.launcher.core.SteamIntegration.ACTION_SETUP, intent.action) + assertEquals("BRIGHTNESS", intent.getStringExtra(com.droiddeck.launcher.core.SteamIntegration.EXTRA_FEATURE)) shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(121)) WriteSettingsShadow.writable = true tick() - assertEquals(192, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) assertTrue(notifications.activeNotifications.isEmpty()) } @@ -123,15 +127,15 @@ class DeviceControlsComponentTest { assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) } - @Test fun rejectedPermissionCanBeRequestedAgainWithoutOpeningRepeatedScreens() { + @Test fun repeatedSliderChangesDoNotInterruptTheSession() { WriteSettingsShadow.writable = false request("brightness", "0.75") - assertNotNull(shadowOf(context).nextStartedActivity) + assertNull(shadowOf(context).nextStartedActivity) request("brightness", "0.8") assertNull(shadowOf(context).nextStartedActivity) shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(5)) request("brightness", "0.8") - assertNotNull(shadowOf(context).nextStartedActivity) + assertNull(shadowOf(context).nextStartedActivity) } @Test fun oversizedRequestsAreDiscardedAndDoNotBlockLaterCommands() { diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt new file mode 100644 index 0000000000..b11fbd2fe1 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt @@ -0,0 +1,93 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assert +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import com.droiddeck.launcher.core.SteamIntegration +import com.droiddeck.launcher.core.SteamIntegration.Feature +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], qualifiers = "w960dp-h540dp-land") +class SteamIntegrationGroupTest { + @get:Rule val compose = createRobolectricComposeRule() + private val state = mutableStateOf(SteamIntegration.State()) + private val requests = mutableListOf() + private var appInfo = 0 + private var location = 0 + + private fun stateIs(value: String) = SemanticsMatcher.expectValue(SemanticsProperties.StateDescription, value) + + private fun show() = compose.setContent { + DroidDeckTheme { + SteamIntegrationGroup(state.value, onFeature = { requests.add(it) }, onAppInfo = { appInfo++ }, onLocation = { location++ }) + } + } + + @Test fun everySwitchRequestsOnlyItsOwnFeature() { + state.value = SteamIntegration.State(home = true) + show() + compose.onNodeWithTag("integration-action-brightness").performClick() + compose.onNodeWithTag("integration-action-home").performClick() + compose.onNodeWithTag("integration-action-shortcuts").performClick() + assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS), requests) + } + + @Test fun switchesReflectAndroidGrants() { + state.value = SteamIntegration.State(brightness = true, home = true, shortcuts = true) + show() + compose.onNodeWithTag("integration-action-brightness").assert(stateIs("On")) + compose.onNodeWithTag("integration-action-shortcuts").assert(stateIs("On")) + compose.onNodeWithTag("integration-action-wifi").assert(stateIs("Off")) + compose.onNodeWithText("3 of 4 on").assertExists() + } + + @Test fun shortcutsWaitForHome() { + show() + compose.onNodeWithTag("integration-action-shortcuts").assertIsNotEnabled() + compose.onNodeWithText("Needs DroidDeck as Home").assertExists() + compose.runOnIdle { state.value = state.value.copy(home = true) } + compose.onNodeWithTag("integration-action-shortcuts").assertIsEnabled() + } + + @Test fun restrictedShortcutsPointToAppInfo() { + state.value = SteamIntegration.State(home = true, shortcutsRestricted = true) + show() + compose.onNodeWithTag("integration-action-shortcuts").assertIsNotEnabled() + compose.onNodeWithText("App info").performClick() + assertEquals(1, appInfo) + compose.runOnIdle { state.value = state.value.copy(shortcutsRestricted = false) } + compose.onNodeWithText("App info").assertDoesNotExist() + compose.onNodeWithTag("integration-action-shortcuts").assertIsEnabled() + } + + @Test fun unconfirmedRestrictionOffersAppInfoAfterAnAttempt() { + state.value = SteamIntegration.State(home = true) + show() + compose.onNodeWithText("App info").assertDoesNotExist() + compose.runOnIdle { state.value = state.value.copy(shortcutsTried = true) } + compose.onNodeWithTag("integration-action-shortcuts").assertIsEnabled() + compose.onNodeWithText("App info").performClick() + assertEquals(1, appInfo) + } + + @Test fun deniedLocationPointsToAppInfoWithoutTogglingWifi() { + state.value = SteamIntegration.State(locationBlocked = true) + show() + compose.onNodeWithText("Location denied · allow it in App info").assertExists() + compose.onNodeWithText("App info").performClick() + assertEquals(1, location) + assertTrue(requests.isEmpty()) + } +}