diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 1ce7b0ac73..6336fb1325 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -27,6 +27,8 @@ + + diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index b9dce0e415..f4bb0b6e2f 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -257,6 +257,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private val cursorResync = Runnable { if (syncClientCursor() && clientHidesCursor) cursorVisible = false } private val uiHandler = Handler(Looper.getMainLooper()) private var pendingBackAction: Runnable? = null + private val backQamInput = com.droiddeck.launcher.input.BackQamInput( + setPressed = { padBridge?.setBackQamPressed(it) }, + onTap = { performBackAction(double = it) }, + ) private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN private var drawerDirectionDownTime = 0L private var drawerDirectionDeviceId = -1 @@ -446,6 +450,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } override fun onInputDeviceRemoved(deviceId: Int) { Log.i(TAG, "input device $deviceId disconnected") + backQamInput.onDeviceRemoved(deviceId) joyConVr?.refresh() padBridge?.onDeviceRemoved(deviceId) if (::padMouse.isInitialized) padMouse.reset() @@ -773,6 +778,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) { if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) { + backQamInput.cancel() cancelTouchGestures() screenKeys?.stopEditing() } @@ -2106,6 +2112,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } private fun releasePads() { + backQamInput.cancel() padBridge?.releaseAll() joyConVr?.releaseButtons() } @@ -2184,6 +2191,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> return super.dispatchKeyEvent(event) } + val backToQam = !pipUi && !screenKeyTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && + SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen && + !SessionState.suspended && padBridge?.canHoldQam() == true + if (backQamInput.onKeyEvent(event, backToQam)) { + pendingBackAction?.let(uiHandler::removeCallbacks) + pendingBackAction = null + return true + } if (pipUi) return true if (screenKeyTextFocus) return super.dispatchKeyEvent(event) val pad = com.droiddeck.launcher.input.JoyCon.normalize(event) @@ -3253,6 +3268,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onPause() { if (runtimeRemovalBlocked) { super.onPause(); return } + backQamInput.cancel() capturePausedFrame() sessionClipboard.stop() if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel() @@ -3636,6 +3652,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) + if (!hasFocus) backQamInput.cancel() if (!hasFocus && ::padMouse.isInitialized) padMouse.reset() if (runtimeRemovalBlocked) return if (!hasFocus) { @@ -3683,6 +3700,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } override fun onDestroy() { + backQamInput.cancel() steamVrRecovery.close() uiHandler.removeCallbacks(steamTouchRetry) if (runtimeRemovalBlocked) { super.onDestroy(); return } diff --git a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java index 3b73b6a3c9..32d5f5189e 100644 --- a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java +++ b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java @@ -26,6 +26,7 @@ public class PulseAudioComponent extends SessionPart { private final File workingDir; + private final File deviceControls; private File logFile; private final String micFifoPath; private volatile int pid = -1; @@ -36,6 +37,8 @@ public class PulseAudioComponent extends SessionPart { public PulseAudioComponent(Context context, String micFifoPath) { this.workingDir = new File(context.getFilesDir(), "pulseaudio"); + this.deviceControls = com.droiddeck.launcher.runtime.DeviceControlsComponent.directory( + com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context)); this.micFifoPath = micFifoPath; } @@ -94,7 +97,7 @@ public class PulseAudioComponent extends SessionPart { config.add("load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0 socket=\"" + socket().getAbsolutePath() + "\""); config.add(".nofail"); - config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0"); + config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls); config.add("set-default-sink DirectAudio"); config.add(".fail"); if (micFifoPath != null && !micFifoPath.isEmpty()) { @@ -139,7 +142,7 @@ public class PulseAudioComponent extends SessionPart { } else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) { line = "== client sink: DirectAudio (module-directaudio-native-sink)"; } else { - boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null + boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null && pactl("set-default-sink", "AAudioSink") != null; line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)" : "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound"; diff --git a/app/src/main/java/com/droiddeck/launcher/input/BackQamInput.kt b/app/src/main/java/com/droiddeck/launcher/input/BackQamInput.kt new file mode 100644 index 0000000000..83e1adafbf --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/BackQamInput.kt @@ -0,0 +1,76 @@ +package com.droiddeck.launcher.input + +import android.view.KeyEvent +import android.os.Handler +import android.os.Looper + +class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap: (Boolean) -> Unit) { + private class Press(val hold: Runnable, var held: Boolean = false, var used: Boolean = false) + private val handler = Handler(Looper.getMainLooper()) + private val presses = mutableMapOf() + private val cancelled = mutableSetOf() + private var tapPending = false + private val singleTap = Runnable { tapPending = false; onTap(false) } + + private fun cancelTap() { + handler.removeCallbacks(singleTap) + tapPending = false + } + + fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean { + if (!enabled) cancel() + if (event.keyCode != KeyEvent.KEYCODE_BACK) return false + val device = event.deviceId + return when (event.action) { + KeyEvent.ACTION_DOWN -> { + if (event.repeatCount > 0) return enabled || device in presses || device in cancelled + cancelled.remove(device) + if (!enabled || event.isCanceled) return false + if (device in presses) return true + handler.removeCallbacks(singleTap) + val hold = Runnable { + val press = presses[device] ?: return@Runnable + val alreadyHeld = presses.values.any { it.held } + press.held = true + presses.values.forEach { it.used = true } + cancelTap() + if (!alreadyHeld) setPressed(true) + } + presses[device] = Press(hold, used = presses.values.any { it.held }) + handler.postDelayed(hold, 700) + true + } + KeyEvent.ACTION_UP -> { + val press = presses.remove(device) + val wasCancelled = cancelled.remove(device) + if (press != null) { + handler.removeCallbacks(press.hold) + if (press.held && presses.values.none { it.held }) setPressed(false) + if (!press.used && !event.isCanceled) { + if (tapPending) { cancelTap(); onTap(true) } + else { tapPending = true; handler.postDelayed(singleTap, 500) } + } else if (event.isCanceled) cancelTap() + } + press != null || wasCancelled || enabled + } + else -> device in presses || device in cancelled + } + } + + fun cancel() { + cancelTap() + val wasHeld = presses.values.any { it.held } + presses.values.forEach { handler.removeCallbacks(it.hold) } + cancelled.addAll(presses.keys) + presses.clear() + if (wasHeld) setPressed(false) + } + + fun onDeviceRemoved(device: Int) { + cancelled.remove(device) + val press = presses.remove(device) ?: return + handler.removeCallbacks(press.hold) + cancelTap() + if (press.held && presses.values.none { it.held }) 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 0811cab05e..2ed8037afd 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java +++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java @@ -61,6 +61,7 @@ public final class PadBridge { private final PadState routedTouch = new PadState(); private boolean systemGuidePressed; private boolean systemQamPressed; + private boolean backQamPressed; private boolean qamChordActive; private int chordButton = -1; private boolean chordButtonPressed; @@ -132,6 +133,7 @@ public final class PadBridge { routedTouch.clear(); systemGuidePressed = false; systemQamPressed = false; + backQamPressed = false; qamTapPressed = false; qamChordActive = false; chordButtonPressed = false; @@ -165,6 +167,7 @@ public final class PadBridge { } systemGuidePressed = false; systemQamPressed = false; + backQamPressed = false; qamChordActive = false; chordButtonPressed = false; qamTapPressed = false; @@ -459,6 +462,7 @@ public final class PadBridge { public synchronized void releaseAll() { routedTouch.clear(); + backQamPressed = false; releaseBackPaddles(); state.clear(); publish(); @@ -479,6 +483,17 @@ public final class PadBridge { return SessionState.getDeckPad() && FakeInputWriter.padHasQam(); } + public boolean canHoldQam() { + return builtinPad && nativeQam(); + } + + public synchronized void setBackQamPressed(boolean pressed) { + if (pressed && !canHoldQam()) return; + if (backQamPressed == pressed) return; + backQamPressed = pressed; + publish(); + } + public synchronized void triggerQam() { if (!builtinPad) return; if (!nativeQam()) { @@ -684,7 +699,7 @@ public final class PadBridge { return; } boolean guide = systemGuidePressed || qamChordActive; - boolean qam = nativeQam() && (systemQamPressed || qamTapPressed); + boolean qam = nativeQam() && (systemQamPressed || qamTapPressed || backQamPressed); if (!guide && !qam) { writer.writePad(state); return; diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt new file mode 100644 index 0000000000..3e0eaf8b21 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt @@ -0,0 +1,195 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import android.content.Intent +import android.app.Notification +import android.app.NotificationChannel +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 +import com.droiddeck.launcher.R +import java.io.File +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import org.json.JSONObject +import kotlin.math.roundToInt + +class DeviceControlsComponent(context: Context, root: File, private val activityVisible: () -> Boolean = { false }) : SessionPart() { + private val context = context.applicationContext + private val audio = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager + 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 previous = "" + private var revision = 0L + init { prepareBacklight(context, root) } + private val observer = object : ContentObserver(handler) { + override fun onChange(selfChange: Boolean) { if (running) publish() } + } + private val requests = object : FileObserver(directory.path, CLOSE_WRITE or MOVED_TO) { + override fun onEvent(event: Int, path: String?) { + if (path in REQUESTS) handler.post { if (running) consume() } + } + } + private val refresh = object : Runnable { + 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) + } + } + publish() + handler.postDelayed(this, 250) + } + } + + fun publish(force: Boolean = false) { + try { + directory.mkdirs() + val level = audio.getStreamVolume(AudioManager.STREAM_MUSIC) + val maximum = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(1) + val muted = audio.isStreamMute(AudioManager.STREAM_MUSIC) + write("volume.state", "$level $maximum ${if (muted) 1 else 0}\n") + val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128) + write("backlight/droiddeck/brightness", "$value\n") + write("backlight/droiddeck/actual_brightness", "$value\n") + val state = JSONObject().put("brightness", (value.coerceIn(1, 255) - 1) / 254.0) + .put("brightnessWritable", Settings.System.canWrite(context)).toString() + if (force || state != previous) { + write("state.json", JSONObject(state).put("revision", ++revision).toString()) + previous = state + } + } catch (e: Exception) { + Log.w(TAG, "Could not publish Android controls", e) + } + } + + override fun start() { + handler.post { + REQUESTS.forEach { + File(directory, it).delete() + File(directory, "$it.processing").delete() + } + running = true + context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, observer) + requests.startWatching() + refresh.run() + } + } + + override fun stop() { + handler.post { + running = false + handler.removeCallbacks(refresh) + requests.stopWatching() + context.contentResolver.unregisterContentObserver(observer) + pendingBrightness = null + context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION) + } + } + + private fun consume() { + for (name in REQUESTS) { + val file = File(directory, name) + if (!file.isFile) continue + val claimed = File(directory, "$name.processing") + try { + Files.move(file.toPath(), claimed.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) + if (claimed.length() > 64) continue + val text = claimed.readText().trim() + when (name) { + "brightness.request" -> text.toFloatOrNull()?.takeIf { it.isFinite() && it in 0f..1f }?.let(::brightness) + "volume.request" -> text.toIntOrNull()?.let { + audio.setStreamVolume(AudioManager.STREAM_MUSIC, + it.coerceIn(0, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)), 0) + } + "mute.request" -> if (text == "0" || text == "1") { + audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, + if (text == "1") AudioManager.ADJUST_MUTE else AudioManager.ADJUST_UNMUTE, 0) + } + } + } catch (e: Exception) { + Log.w(TAG, "Could not apply $name", e) + } finally { + publish(force = true) + claimed.delete() + } + } + } + + private fun brightness(value: Float) { + if (!Settings.System.canWrite(context)) { + pendingBrightness = value + val now = SystemClock.elapsedRealtime() + if (now - permissionRequestAt >= 5_000) { + permissionRequestAt = now + try { + val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, + Uri.parse("package:${context.packageName}")).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + val manager = context.getSystemService(NotificationManager::class.java) + manager.createNotificationChannel(NotificationChannel(PERMISSION_CHANNEL, + context.getString(R.string.brightness_permission_title), NotificationManager.IMPORTANCE_DEFAULT)) + val action = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE) + manager.notify(PERMISSION_NOTIFICATION, Notification.Builder(context, PERMISSION_CHANNEL) + .setSmallIcon(R.drawable.ic_stat_session) + .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) + } catch (e: Exception) { + Log.w(TAG, "Could not open brightness permission", e) + } + } + return + } + val level = 1 + (value * 254).roundToInt() + try { + Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, + Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL) + Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, level) + } catch (e: SecurityException) { + Log.w(TAG, "Brightness permission was revoked", e) + } + } + + private fun write(name: String, text: String) { + val file = File(directory, name) + if (file.isFile && file.readText() == text) return + val staged = File(directory, "$name.tmp") + staged.writeText(text) + Files.move(staged.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) + } + + companion object { + private const val TAG = "DeviceControls" + private const val PERMISSION_CHANNEL = "brightness_permission" + private const val PERMISSION_NOTIFICATION = 0x4442 + private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request") + @JvmStatic fun directory(root: File) = File(root, "etc/droiddeck-device-controls") + @JvmStatic fun prepareBacklight(context: Context, root: File): File { + val base = File(directory(root), "backlight") + val panel = File(base, "droiddeck").apply { mkdirs() } + val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128) + for ((name, text) in mapOf("type" to "raw", "max_brightness" to "255", "brightness" to "$value", + "actual_brightness" to "$value", "bl_power" to "0", "scale" to "linear")) { + File(panel, name).writeText("$text\n") + } + return base + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java index 6473197549..d02fdf0c2f 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java @@ -192,6 +192,7 @@ public final class LinuxRuntime { bind(cmd, "/dev"); bind(cmd, "/proc"); bind(cmd, "/sys"); + bind(cmd, DeviceControlsComponent.prepareBacklight(context, root).getPath() + ":/sys/class/backlight"); bind(cmd, "/dev/urandom:/dev/random"); bind(cmd, "/proc/self/fd:/dev/fd"); bind(cmd, "/proc/self/fd/0:/dev/stdin"); 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 c85f11bbaf..be9795042a 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -630,6 +630,10 @@ class SessionService : Service() { networkLink.attach(this) networkLink.publish() components.add(networkLink) + val deviceControls = com.droiddeck.launcher.runtime.DeviceControlsComponent(this, root) { activityVisible && screenOn } + deviceControls.attach(this) + deviceControls.publish() + components.add(deviceControls) if (gen != sessionGen || !SessionState.running) { Log.i(TAG, "session stopped while it was starting; not launching it") if (gen == sessionGen) components.clear() 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 431858bf05..f8f8857645 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -313,6 +313,9 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU), ), s.backActionsInverted, onPick = a.onBackActionsInverted, ) + if (steam && s.steamController in listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM)) { + Note(stringResource(R.string.back_native_qam_hint)) + } } } if (tab == SheetTab.AUDIO && steam) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 6b598b8c25..840e26ebb6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -306,6 +306,9 @@ Xbox 360 controller Deck: Quick Access button and gyro. Steam Controller: the same, with grip sense on the back buttons. DualShock 4 and DualSense: gyro, and the trackpads as their touchpad. Xbox 360: open Quick Access with Guide+A. Back + Hold Back for 700 ms, then press another button for Steam shortcuts. Single and double taps keep the selected actions. + Allow brightness control + Tap to allow Steam to change Android screen brightness. Menu → QAM QAM → Menu Session diff --git a/app/src/test/java/com/droiddeck/launcher/input/BackQamInputTest.kt b/app/src/test/java/com/droiddeck/launcher/input/BackQamInputTest.kt new file mode 100644 index 0000000000..8006a495b2 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/BackQamInputTest.kt @@ -0,0 +1,175 @@ +package com.droiddeck.launcher.input + +import android.os.Looper +import android.view.KeyEvent +import java.time.Duration +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], manifest = Config.NONE) +class BackQamInputTest { + private val changes = mutableListOf() + private val taps = mutableListOf() + private val input = BackQamInput(changes::add, taps::add) + + @Test fun singleTapWaitsForTheDoubleTapWindowWithoutPressingQam() { + send(KeyEvent.ACTION_DOWN) + advance(100) + send(KeyEvent.ACTION_UP) + advance(499) + assertTrue(taps.isEmpty()) + advance(1) + assertEquals(listOf(false), taps) + assertTrue(changes.isEmpty()) + } + + @Test fun doubleTapProducesOnlyTheDoubleAction() { + repeat(2) { + send(KeyEvent.ACTION_DOWN) + advance(100) + send(KeyEvent.ACTION_UP) + advance(100) + } + advance(1000) + assertEquals(listOf(true), taps) + assertTrue(changes.isEmpty()) + } + + @Test fun aHoldStartsAt700msAndNeverProducesATap() { + assertTrue(send(KeyEvent.ACTION_DOWN)) + advance(699) + assertTrue(changes.isEmpty()) + advance(1) + for (repeat in 1..10) assertTrue(send(KeyEvent.ACTION_DOWN, repeat = repeat)) + advance(4000) + assertEquals(listOf(true), changes) + assertTrue(send(KeyEvent.ACTION_UP)) + advance(1000) + assertEquals(listOf(true, false), changes) + assertTrue(taps.isEmpty()) + } + + @Test fun releasingBetween500And700msStillProducesASingleTap() { + send(KeyEvent.ACTION_DOWN) + advance(600) + send(KeyEvent.ACTION_UP) + advance(500) + assertEquals(listOf(false), taps) + assertTrue(changes.isEmpty()) + } + + @Test fun holdingTheSecondPressCancelsTheFirstTap() { + send(KeyEvent.ACTION_DOWN) + send(KeyEvent.ACTION_UP) + advance(400) + send(KeyEvent.ACTION_DOWN) + advance(699) + assertTrue(taps.isEmpty()) + advance(1) + assertEquals(listOf(true), changes) + send(KeyEvent.ACTION_UP) + advance(1000) + assertTrue(taps.isEmpty()) + } + + @Test fun otherButtonsAndSelectPassThroughWhileBackIsHeld() { + send(KeyEvent.ACTION_DOWN) + advance(700) + for (code in listOf(KeyEvent.KEYCODE_BUTTON_X, KeyEvent.KEYCODE_BUTTON_SELECT)) { + for (action in listOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP)) { + assertFalse(input.onKeyEvent(KeyEvent(action, code), true)) + } + } + assertEquals(listOf(true), changes) + send(KeyEvent.ACTION_UP) + assertEquals(listOf(true, false), changes) + } + + @Test fun disabledRoutingPreservesBackNavigation() { + assertFalse(send(KeyEvent.ACTION_DOWN, enabled = false)) + assertFalse(send(KeyEvent.ACTION_UP, enabled = false)) + assertTrue(changes.isEmpty()) + assertTrue(taps.isEmpty()) + } + + @Test fun losingFocusReleasesQamAndConsumesTheLateRelease() { + send(KeyEvent.ACTION_DOWN) + advance(700) + input.cancel() + input.cancel() + assertTrue(send(KeyEvent.ACTION_DOWN, repeat = 1, enabled = false)) + assertTrue(send(KeyEvent.ACTION_UP, enabled = false)) + advance(1000) + assertEquals(listOf(true, false), changes) + assertTrue(taps.isEmpty()) + } + + @Test fun cancellationBeforeTheThresholdPreventsBothHoldAndTap() { + send(KeyEvent.ACTION_DOWN) + advance(100) + input.cancel() + send(KeyEvent.ACTION_UP) + advance(1000) + assertTrue(changes.isEmpty()) + assertTrue(taps.isEmpty()) + } + + @Test fun cancellationAlsoDiscardsAPendingSingleTap() { + send(KeyEvent.ACTION_DOWN) + send(KeyEvent.ACTION_UP) + input.cancel() + advance(1000) + assertTrue(taps.isEmpty()) + } + + @Test fun openingAnOverlayReleasesQamBeforeRoutingItsNextKey() { + send(KeyEvent.ACTION_DOWN) + advance(700) + assertFalse(input.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_B), false)) + assertTrue(send(KeyEvent.ACTION_UP, enabled = false)) + assertEquals(listOf(true, false), changes) + } + + @Test fun repeatsAfterCancellationCannotReassertQam() { + send(KeyEvent.ACTION_DOWN) + advance(700) + input.cancel() + assertTrue(send(KeyEvent.ACTION_DOWN, repeat = 1)) + advance(1000) + assertEquals(listOf(true, false), changes) + assertTrue(send(KeyEvent.ACTION_DOWN)) + advance(700) + assertTrue(send(KeyEvent.ACTION_UP)) + assertEquals(listOf(true, false, true, false), changes) + } + + @Test fun cancelledReleaseNeverProducesATap() { + send(KeyEvent.ACTION_DOWN) + assertTrue(input.onKeyEvent(KeyEvent(0, 100, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK, + 0, 0, 4, 0, KeyEvent.FLAG_CANCELED), true)) + advance(1000) + assertTrue(changes.isEmpty()) + assertTrue(taps.isEmpty()) + } + + @Test fun removingOneDeviceDoesNotReleaseAnotherDevicesHold() { + send(KeyEvent.ACTION_DOWN, device = 4) + send(KeyEvent.ACTION_DOWN, device = 5) + advance(700) + input.onDeviceRemoved(4) + assertEquals(listOf(true), changes) + send(KeyEvent.ACTION_UP, device = 5) + assertEquals(listOf(true, false), changes) + assertTrue(taps.isEmpty()) + } + + private fun advance(millis: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(millis)) + + private fun send(action: Int, repeat: Int = 0, device: Int = 4, enabled: Boolean = true) = + input.onKeyEvent(KeyEvent(0, 100, action, KeyEvent.KEYCODE_BACK, repeat, 0, device, 0), enabled) +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt new file mode 100644 index 0000000000..3491076a24 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt @@ -0,0 +1,115 @@ +package com.droiddeck.launcher.input + +import android.os.Handler +import com.droiddeck.launcher.session.SessionState +import java.nio.file.Files +import java.time.Duration +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.util.ReflectionHelpers + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], manifest = Config.NONE, instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter"], + shadows = [JoyConPadTest.RecordingWriter::class]) +class PadBridgeQamTest { + private val directory = Files.createTempDirectory("qam-pad").toFile() + private lateinit var bridge: PadBridge + + @Before fun start() { + JoyConPadTest.RecordingWriter.pads.clear() + ReflectionHelpers.setStaticField(FakeInputWriter::class.java, "padType", FakeInputWriter.PAD_TYPE_DECK) + SessionState.deckPad = true + bridge = PadBridge(directory) + assertTrue(bridge.start()) + } + + @After fun stop() { + bridge.stop() + SessionState.deckPad = false + directory.deleteRecursively() + } + + @Test fun onlyNativeQamControllersAcceptAHeldBack() { + for (type in listOf(-1, FakeInputWriter.PAD_TYPE_DECK, FakeInputWriter.PAD_TYPE_STEAM, + FakeInputWriter.PAD_TYPE_XBOX, FakeInputWriter.PAD_TYPE_DS4, FakeInputWriter.PAD_TYPE_DUALSENSE)) { + ReflectionHelpers.setStaticField(FakeInputWriter::class.java, "padType", type) + val supported = type <= FakeInputWriter.PAD_TYPE_STEAM + assertEquals(supported, bridge.canHoldQam()) + bridge.setBackQamPressed(true) + bridge.applyExternal({}, false) + assertEquals(supported, pad().isDown(PadState.QAM)) + bridge.setBackQamPressed(false) + } + SessionState.deckPad = false + assertFalse(bridge.canHoldQam()) + } + + @Test fun qamAndOtherButtonsShareAReportUntilBackIsReleased() { + bridge.setBackQamPressed(true) + advanceTime() + bridge.applyExternal({ it.press(PadState.X, true); it.press(PadState.SELECT, true) }, true) + assertTrue(pad().isDown(PadState.QAM)) + assertTrue(pad().isDown(PadState.X)) + assertTrue(pad().isDown(PadState.SELECT)) + bridge.setBackQamPressed(false) + assertFalse(pad().isDown(PadState.QAM)) + assertTrue(pad().isDown(PadState.X)) + assertTrue(pad().isDown(PadState.SELECT)) + } + + @Test fun touchQamAndBackHaveIndependentReleases() { + bridge.setBackQamPressed(true) + bridge.setSystemButtons(false, true) + bridge.setBackQamPressed(false) + assertTrue(pad().isDown(PadState.QAM)) + bridge.setBackQamPressed(true) + bridge.setSystemButtons(false, false) + assertTrue(pad().isDown(PadState.QAM)) + bridge.setBackQamPressed(false) + assertFalse(pad().isDown(PadState.QAM)) + } + + @Test fun aTimedQamTapCannotReleaseAHeldBack() { + bridge.triggerQam() + bridge.setBackQamPressed(true) + advanceTime() + assertTrue(pad().isDown(PadState.QAM)) + bridge.setBackQamPressed(false) + assertFalse(pad().isDown(PadState.QAM)) + } + + @Test fun releasingAllOrStoppingClearsTheHold() { + bridge.setBackQamPressed(true) + bridge.releaseAll() + assertFalse(pad().isDown(PadState.QAM)) + bridge.setBackQamPressed(true) + bridge.stop() + bridge.start() + bridge.applyExternal({}, false) + assertFalse(pad().isDown(PadState.QAM)) + } + + @Test fun disablingTheBuiltinPadClearsAndRejectsTheHold() { + bridge.setBackQamPressed(true) + bridge.setBuiltinPad(false) + assertFalse(bridge.canHoldQam()) + assertFalse(pad().isDown(PadState.QAM)) + bridge.setBackQamPressed(true) + bridge.setBuiltinPad(true) + bridge.applyExternal({}, false) + assertFalse(pad().isDown(PadState.QAM)) + } + + private fun pad() = requireNotNull(JoyConPadTest.RecordingWriter.pads[0]) + + private fun advanceTime() { + val handler = ReflectionHelpers.getStaticField(PadBridge::class.java, "chordHandler") + shadowOf(handler.looper).idleFor(Duration.ofSeconds(2)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt new file mode 100644 index 0000000000..fa96dacc99 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/DeviceControlsComponentTest.kt @@ -0,0 +1,151 @@ +package com.droiddeck.launcher.runtime + +import android.app.Application +import android.app.NotificationManager +import android.content.Context +import android.media.AudioManager +import android.os.Looper +import android.provider.Settings +import java.io.File +import java.time.Duration +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.annotation.Implements +import org.robolectric.annotation.Implementation +import org.robolectric.shadows.ShadowSettings + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28, 33], manifest = Config.NONE, application = Application::class, shadows = [WriteSettingsShadow::class]) +class DeviceControlsComponentTest { + @get:Rule val tmp = TemporaryFolder() + private val context get() = RuntimeEnvironment.getApplication() + private val audio get() = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager + private lateinit var component: DeviceControlsComponent + private lateinit var directory: File + private var visible = true + + @Before fun start() { + WriteSettingsShadow.writable = true + Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128) + val root = tmp.newFolder() + directory = DeviceControlsComponent.directory(root) + component = DeviceControlsComponent(context, root) { visible } + component.publish() + component.start() + shadowOf(Looper.getMainLooper()).idle() + } + + @After fun stop() { + component.stop() + shadowOf(Looper.getMainLooper()).idle() + } + + private fun tick() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(300)) + private fun request(name: String, text: String) { + File(directory, "$name.request").writeText(text) + tick() + } + + @Test fun androidChangesArePublishedAndRequestsUseDeviceVolumeSteps() { + request("volume", "999") + assertEquals(audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC), audio.getStreamVolume(AudioManager.STREAM_MUSIC)) + audio.setStreamVolume(AudioManager.STREAM_MUSIC, 3, 0) + tick() + assertEquals("3", File(directory, "volume.state").readText().split(" ").first()) + request("volume", "invalid") + assertEquals(3, audio.getStreamVolume(AudioManager.STREAM_MUSIC)) + } + + @Test fun deniedBrightnessIsReadBackAndAppliedOnlyAfterPermission() { + 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) + assertFalse(JSONObject(File(directory, "state.json").readText()).getBoolean("brightnessWritable")) + WriteSettingsShadow.writable = true + tick() + assertEquals(192, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + } + + @Test fun brightnessIsBoundedAndExternalChangesAreReadBack() { + for (invalid in listOf("NaN", "Infinity", "-0.1", "1.1")) request("brightness", invalid) + assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + request("brightness", "0") + assertEquals(1, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 255) + tick() + assertEquals(1.0, JSONObject(File(directory, "state.json").readText()).getDouble("brightness"), 0.0001) + } + + @Test fun hiddenPermissionRequestOffersANotificationAndRetainsTheLatestValue() { + visible = false + WriteSettingsShadow.writable = false + request("brightness", "0.25") + request("brightness", "0.75") + assertNull(shadowOf(context).nextStartedActivity) + 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) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(121)) + WriteSettingsShadow.writable = true + tick() + assertEquals(192, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + assertTrue(notifications.activeNotifications.isEmpty()) + } + + @Test fun stoppingClearsThePermissionNotificationAndPendingRequest() { + visible = false + WriteSettingsShadow.writable = false + request("brightness", "0.75") + component.stop() + shadowOf(Looper.getMainLooper()).idle() + assertTrue(context.getSystemService(NotificationManager::class.java).activeNotifications.isEmpty()) + WriteSettingsShadow.writable = true + tick() + assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + } + + @Test fun stoppedSessionsDoNotConsumeNewCommands() { + component.stop() + shadowOf(Looper.getMainLooper()).idle() + request("brightness", "0.2") + assertEquals(128, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + } + + @Test fun rejectedPermissionCanBeRequestedAgainWithoutOpeningRepeatedScreens() { + WriteSettingsShadow.writable = false + request("brightness", "0.75") + assertNotNull(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) + } + + @Test fun oversizedRequestsAreDiscardedAndDoNotBlockLaterCommands() { + request("brightness", "0".repeat(1000)) + assertFalse(File(directory, "brightness.request.processing").exists()) + request("brightness", "0.75") + assertEquals(192, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)) + } +} + +@Implements(Settings.System::class) +class WriteSettingsShadow : ShadowSettings.ShadowSystem() { + companion object { + @JvmField var writable = true + @JvmStatic @Implementation fun canWrite(context: Context) = writable + } +} diff --git a/tools/aaudio-sink/android-volume.h b/tools/aaudio-sink/android-volume.h new file mode 100644 index 0000000000..6a31befeb1 --- /dev/null +++ b/tools/aaudio-sink/android-volume.h @@ -0,0 +1,103 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +#include +#include +#include + +struct android_volume { + pa_sink *sink; + char *directory; + pa_time_event *timer; +}; + +static bool android_volume_read(const char *directory, unsigned *level, unsigned *maximum, unsigned *muted) { + char *path = pa_sprintf_malloc("%s/volume.state", directory); + FILE *file = fopen(path, "r"); + pa_xfree(path); + if (!file) return false; + int fields = fscanf(file, "%u %u %u", level, maximum, muted); + fclose(file); + return fields == 3 && *maximum > 0 && *level <= *maximum && *muted <= 1; +} + +static void android_volume_request(pa_sink *sink, const char *name, unsigned value) { + struct userdata *u = sink->userdata; + if (!u->android_volume || sink->state == PA_SINK_INIT) return; + char *path = pa_sprintf_malloc("%s/%s.request", u->android_volume->directory, name); + char *staged = pa_sprintf_malloc("%s.tmp", path); + FILE *file = fopen(staged, "w"); + if (file) { + fprintf(file, "%u\n", value); + if (fclose(file) == 0 && rename(staged, path) < 0) pa_log_warn("Could not publish Android %s", name); + } + pa_xfree(staged); + pa_xfree(path); +} + +static void android_volume_set(pa_sink *sink) { + struct userdata *u = sink->userdata; + unsigned level, maximum, muted; + if (!u->android_volume || !android_volume_read(u->android_volume->directory, &level, &maximum, &muted)) return; + unsigned requested = PA_MIN(pa_cvolume_max(&sink->real_volume), PA_VOLUME_NORM); + level = ((uint64_t)requested * maximum + PA_VOLUME_NORM / 2) / PA_VOLUME_NORM; + pa_cvolume_set(&sink->real_volume, sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum); + /* Android applies media gain to both PulseAudio and DirectAudio streams. */ + pa_cvolume_reset(&sink->soft_volume, sink->sample_spec.channels); + android_volume_request(sink, "volume", level); +} + +static void android_volume_mute(pa_sink *sink) { + android_volume_request(sink, "mute", sink->muted ? 1 : 0); +} + +static void android_volume_refresh(pa_mainloop_api *api, pa_time_event *event, const struct timeval *tv, void *userdata) { + struct android_volume *bridge = userdata; + unsigned level, maximum, muted; + char *request = pa_sprintf_malloc("%s/volume.request", bridge->directory); + char *mute_request = pa_sprintf_malloc("%s/mute.request", bridge->directory); + char *processing = pa_sprintf_malloc("%s.processing", request); + char *mute_processing = pa_sprintf_malloc("%s.processing", mute_request); + if (access(request, F_OK) != 0 && access(mute_request, F_OK) != 0 && + access(processing, F_OK) != 0 && access(mute_processing, F_OK) != 0 && + android_volume_read(bridge->directory, &level, &maximum, &muted)) { + pa_cvolume volume; + if (bridge->sink->n_volume_steps != maximum + 1) { + bridge->sink->n_volume_steps = maximum + 1; + pa_subscription_post(bridge->sink->core, PA_SUBSCRIPTION_EVENT_SINK | PA_SUBSCRIPTION_EVENT_CHANGE, bridge->sink->index); + } + pa_cvolume_set(&volume, bridge->sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum); + if (!pa_cvolume_equal(&volume, &bridge->sink->real_volume)) pa_sink_volume_changed(bridge->sink, &volume); + if (bridge->sink->muted != !!muted) pa_sink_mute_changed(bridge->sink, !!muted); + } + pa_xfree(request); + pa_xfree(mute_request); + pa_xfree(processing); + pa_xfree(mute_processing); + pa_core_rttime_restart(bridge->sink->core, event, pa_rtclock_now() + 100 * PA_USEC_PER_MSEC); +} + +static struct android_volume *android_volume_new(pa_sink *sink, const char *directory) { + unsigned level, maximum, muted; + if (!directory) return NULL; + struct android_volume *bridge = pa_xnew0(struct android_volume, 1); + bridge->sink = sink; + bridge->directory = pa_xstrdup(directory); + if (android_volume_read(directory, &level, &maximum, &muted)) { + pa_cvolume_set(&sink->real_volume, sink->sample_spec.channels, (uint64_t)level * PA_VOLUME_NORM / maximum); + sink->reference_volume = sink->real_volume; + sink->muted = !!muted; + sink->n_volume_steps = maximum + 1; + } + pa_cvolume_reset(&sink->soft_volume, sink->sample_spec.channels); + pa_sink_set_set_volume_callback(sink, android_volume_set); + pa_sink_set_set_mute_callback(sink, android_volume_mute); + bridge->timer = pa_core_rttime_new(sink->core, pa_rtclock_now() + 100 * PA_USEC_PER_MSEC, + android_volume_refresh, bridge); + return bridge; +} + +static void android_volume_free(struct android_volume *bridge) { + if (!bridge) return; + bridge->sink->core->mainloop->time_free(bridge->timer); + pa_xfree(bridge->directory); + pa_xfree(bridge); +} diff --git a/tools/aaudio-sink/module-aaudio-sink.c b/tools/aaudio-sink/module-aaudio-sink.c index 619bd26733..e79a20a54a 100644 --- a/tools/aaudio-sink/module-aaudio-sink.c +++ b/tools/aaudio-sink/module-aaudio-sink.c @@ -42,6 +42,7 @@ PA_MODULE_USAGE( "channels= " "channel_map= " "volume= " + "control_dir= " "performance_mode=<0 none, 1 low latency, 2 power saving> " "adaptive= " "buffer_frames= " @@ -56,6 +57,7 @@ PA_MODULE_USAGE( #define STATS_EVERY_USEC (30 * PA_USEC_PER_SEC) static const char* const valid_modargs[] = { + "control_dir", "sink_name", "sink_properties", "format", @@ -70,7 +72,10 @@ static const char* const valid_modargs[] = { NULL }; +struct android_volume; + struct userdata { + struct android_volume *android_volume; pa_core *core; pa_module *module; pa_sink *sink; @@ -100,6 +105,9 @@ struct userdata { int32_t xruns_reported; }; +#include "android-volume.h" + + static pa_usec_t frames_to_usec(const struct userdata *u, int64_t frames) { return (pa_usec_t) (frames * (int64_t) PA_USEC_PER_SEC / (int64_t) u->ss.rate); } @@ -472,6 +480,7 @@ int pa__init(pa_module *m) { goto fail; } + u->android_volume = android_volume_new(u->sink, pa_modargs_get_value(ma, "control_dir", NULL)); pa_sink_put(u->sink); pa_modargs_free(ma); return 0; @@ -498,6 +507,8 @@ void pa__done(pa_module *m) { if (!(u = m->userdata)) return; + android_volume_free(u->android_volume); + u->android_volume = NULL; if (u->sink) pa_sink_unlink(u->sink); if (u->thread) { diff --git a/tools/directaudio/sink/module-directaudio-native-sink.c b/tools/directaudio/sink/module-directaudio-native-sink.c index ca3eb01cc5..3b6e5f6c9c 100644 --- a/tools/directaudio/sink/module-directaudio-native-sink.c +++ b/tools/directaudio/sink/module-directaudio-native-sink.c @@ -59,6 +59,7 @@ PA_MODULE_DESCRIPTION("Android audio output: DirectAudio's AAudio engine, in-pro PA_MODULE_VERSION(PACKAGE_VERSION); PA_MODULE_LOAD_ONCE(false); PA_MODULE_USAGE( + "control_dir= " "sink_name= " "sink_properties= " "volume= " @@ -91,11 +92,15 @@ PA_MODULE_USAGE( #define DA_FADE_FRAMES 64 static const char* const valid_modargs[] = { + "control_dir", "sink_name", "sink_properties", "volume", "performance_mode", "buffer_ms", "max_ms", "ring_ms", "adaptive", "decay", "limiter", "watchdog", NULL }; +struct android_volume; + struct userdata { + struct android_volume *android_volume; pa_core *core; pa_module *module; pa_sink *sink; @@ -136,6 +141,9 @@ struct userdata { unsigned int opens; }; +#include "../../aaudio-sink/android-volume.h" + + static uint64_t now_ns(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); @@ -774,6 +782,7 @@ int pa__init(pa_module *m) { pa_log("Failed to create thread."); goto fail; } + u->android_volume = android_volume_new(u->sink, pa_modargs_get_value(ma, "control_dir", NULL)); pa_sink_put(u->sink); pa_modargs_free(ma); return 0; @@ -799,6 +808,8 @@ void pa__done(pa_module *m) { pa_assert(m); if (!(u = m->userdata)) return; + android_volume_free(u->android_volume); + u->android_volume = NULL; if (u->sink) pa_sink_unlink(u->sink); if (u->thread) { diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat index ba739235b1..126afe0505 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat @@ -2,6 +2,7 @@ import base64 import ctypes import json +import math import os import runpy import select @@ -15,6 +16,50 @@ import time HERE = os.path.dirname(os.path.realpath(__file__)) COMPAT = runpy.run_path(os.path.join(HERE, "steam-compatibility")) BINDING = "droiddeckCompatChanged" +BRIGHTNESS_BINDING = "droiddeckBrightnessChanged" +CONTROLS_DIR = "/etc/droiddeck-device-controls" +BRIGHTNESS_JS = r""" +(() => { + if (window.__droiddeckBrightness) return "present"; + const display = SteamClient.System?.Display; + if (!display?.RegisterForBrightnessChanges || !display?.SetBrightness) return "unavailable"; + const self = { expected: null, updating: true, revision: 0 }; + self.set = value => { + if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) return; + if (!self.updating && self.expected !== null && Math.abs(value - self.expected) < 0.0001) return; + self.expected = value; + self.updating = true; + const revision = ++self.revision; + setTimeout(() => { if (self.revision === revision) self.updating = false; }, 500); + display.SetBrightness(value); + }; + self.subscription = display.RegisterForBrightnessChanges(state => { + const value = state?.flBrightness; + if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1 || self.expected === null) return; + if (Math.abs(value - self.expected) < 0.0001) { self.updating = false; return; } + if (self.updating) { self.updating = false; return; } + self.expected = value; + if (typeof window.__BINDING__ === "function") window.__BINDING__(String(value)); + }); + window.__droiddeckBrightness = self; + return "installed"; +})() +""".replace("__BINDING__", BRIGHTNESS_BINDING) + + +def brightness_request(payload, directory=CONTROLS_DIR): + try: + value = float(payload) + if not math.isfinite(value) or not 0 <= value <= 1: + return + path = os.path.join(directory, "brightness.request") + with open(path + ".tmp", "w") as target: + target.write(str(value) + "\n") + os.replace(path + ".tmp", path) + except (ValueError, TypeError, OSError): + return + + INSTALL_JS = r""" (() => { if (window.__droiddeckCompat) return "present"; @@ -633,6 +678,29 @@ class Helper: self.tools_checked = None self.vr_launch = None self.chooser = None + self.controls_state = None + self.controls_installed = False + + def sync_controls(self): + try: + with open(os.path.join(CONTROLS_DIR, "state.json")) as source: + state = json.load(source) + value = state.get("brightness") + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not 0 <= value <= 1: + return + if not self.controls_installed: + self.page.call("Runtime.addBinding", {"name": BRIGHTNESS_BINDING}) + self.controls_installed = self.page.evaluate(BRIGHTNESS_JS) in ("installed", "present") + if not self.controls_installed: + return + if state != self.controls_state: + if self.page.evaluate("!!window.__droiddeckBrightness && (window.__droiddeckBrightness.set(%s), true)" % json.dumps(value)) is True: + self.controls_state = state + else: + self.controls_installed = False + self.controls_state = None + except (OSError, ValueError, TypeError): + pass def open_chooser(self, payload): try: @@ -709,6 +777,9 @@ class Helper: page.call("Runtime.addBinding", {"name": FILE_BINDING}) page.evaluate(FILE_JS) self.page = page + self.controls_state = None + self.controls_installed = False + self.sync_controls() return True page.call("Runtime.addBinding", {"name": BINDING}) page.call("Runtime.addBinding", {"name": VR_BINDING}) @@ -728,6 +799,9 @@ class Helper: page.ws.close() raise self.page = page + self.controls_state = None + self.controls_installed = False + self.sync_controls() return True def reconcile(self): @@ -854,6 +928,8 @@ class Helper: say("preparing SteamVR for library app(s): " + ", ".join(sorted(vr_games))) self.vr_launch = launch_steamvr() for e in events: + if called(e, BRIGHTNESS_BINDING): + brightness_request(e.get("params", {}).get("payload")) if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str): self.open_chooser(e["params"]["payload"]) return events @@ -861,15 +937,14 @@ class Helper: def serve_files(self): say("attached to the client on port %d for its file dialogs" % self.port) while True: + self.sync_controls() sources = [self.page.ws] + ([self.chooser[1].stdout] if self.chooser is not None else []) queued = self.page.ws.pending() or bool(self.page.events) - ready = [self.page.ws] if queued else select.select(sources, [], [], 30)[0] + ready = [self.page.ws] if queued else select.select(sources, [], [], 0.25)[0] if self.chooser is not None and self.chooser[1].stdout in ready: self.chooser_done() if self.page.ws in ready or self.page.events: - for e in self.page.drain(): - if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str): - self.open_chooser(e["params"]["payload"]) + self.drain() def serve(self, watcher): if self.files_only: @@ -880,10 +955,12 @@ class Helper: self.reconcile() self.ensure_tools() while True: + self.sync_controls() sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else []) if self.chooser is not None: sources.append(self.chooser[1].stdout) - ready = [self.page.ws] if self.page.ws.pending() else select.select(sources, [], [], 30 if watcher.fileno() >= 0 else 2)[0] + queued = self.page.ws.pending() or bool(self.page.events) + ready = [self.page.ws] if queued else select.select(sources, [], [], 0.25)[0] if self.chooser is not None and self.chooser[1].stdout in ready: self.chooser_done() due = False diff --git a/tools/tests/test_android_volume.py b/tools/tests/test_android_volume.py new file mode 100644 index 0000000000..8246f34fe1 --- /dev/null +++ b/tools/tests/test_android_volume.py @@ -0,0 +1,101 @@ +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +@unittest.skipUnless(shutil.which("cc"), "C compiler required") +class AndroidVolumeTest(unittest.TestCase): + def test_missing_or_invalid_initial_state_recovers_without_restarting_the_sink(self): + header = Path(__file__).resolve().parents[1] / "aaudio-sink/android-volume.h" + harness = r''' +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define PA_VOLUME_NORM 65536U +#define PA_USEC_PER_MSEC 1000 +#define PA_SINK_INIT 0 +#define PA_SUBSCRIPTION_EVENT_SINK 1 +#define PA_SUBSCRIPTION_EVENT_CHANGE 2 +#define PA_MIN(a,b) ((a)<(b)?(a):(b)) +#define pa_xnew0(type,n) ((type*)calloc(n,sizeof(type))) +#define pa_xstrdup strdup +#define pa_xfree free +#define pa_log_warn(...) ((void)0) +typedef struct { unsigned value; } pa_cvolume; +typedef struct pa_time_event { int value; } pa_time_event; +typedef struct pa_mainloop_api { void (*time_free)(pa_time_event*); } pa_mainloop_api; +typedef struct { pa_mainloop_api *mainloop; } pa_core; +typedef struct pa_sink { + void *userdata; int state; bool muted; unsigned n_volume_steps, index; + struct { unsigned channels; } sample_spec; + pa_cvolume real_volume, reference_volume, soft_volume; + pa_core *core; + void (*set_volume)(struct pa_sink*), (*set_mute)(struct pa_sink*); +} pa_sink; +struct android_volume; +struct userdata { struct android_volume *android_volume; }; +static int restarts, frees; +static char *pa_sprintf_malloc(const char *format, ...) { + va_list ap; va_start(ap,format); char *result; assert(vasprintf(&result,format,ap)>=0); va_end(ap); return result; +} +static void pa_cvolume_set(pa_cvolume *volume, unsigned channels, unsigned value) { volume->value=value; } +static unsigned pa_cvolume_max(const pa_cvolume *volume) { return volume->value; } +static void pa_cvolume_reset(pa_cvolume *volume, unsigned channels) { volume->value=PA_VOLUME_NORM; } +static bool pa_cvolume_equal(const pa_cvolume *a, const pa_cvolume *b) { return a->value==b->value; } +static void pa_sink_volume_changed(pa_sink *sink, const pa_cvolume *volume) { sink->real_volume=*volume; } +static void pa_sink_mute_changed(pa_sink *sink, bool muted) { sink->muted=muted; } +static void pa_sink_set_set_volume_callback(pa_sink *sink, void (*callback)(pa_sink*)) { sink->set_volume=callback; } +static void pa_sink_set_set_mute_callback(pa_sink *sink, void (*callback)(pa_sink*)) { sink->set_mute=callback; } +static void pa_subscription_post(pa_core *core, int event, unsigned index) {} +static uint64_t pa_rtclock_now(void) { return 0; } +static void pa_core_rttime_restart(pa_core *core, pa_time_event *event, uint64_t time) { restarts++; } +static pa_time_event *pa_core_rttime_new(pa_core *core, uint64_t time, + void (*callback)(pa_mainloop_api*,pa_time_event*,const struct timeval*,void*), void *userdata) { + return calloc(1,sizeof(pa_time_event)); +} +static void free_timer(pa_time_event *event) { frees++; free(event); } +#include "android-volume.h" +static void state(const char *directory, const char *text) { + char *path=pa_sprintf_malloc("%s/volume.state",directory); + FILE *f=fopen(path,"w"); assert(f); fputs(text,f); fclose(f); free(path); +} +int main(int argc, char **argv) { + pa_mainloop_api api={.time_free=free_timer}; pa_core core={.mainloop=&api}; + struct userdata userdata={0}; + pa_sink sink={.userdata=&userdata,.core=&core,.state=1,.sample_spec={.channels=2},.real_volume={PA_VOLUME_NORM}}; + userdata.android_volume=android_volume_new(&sink,argv[1]); + assert(userdata.android_volume && userdata.android_volume->timer && sink.set_volume && sink.set_mute); + state(argv[1],"invalid\n"); + android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume); + assert(sink.real_volume.value==PA_VOLUME_NORM && restarts==1); + state(argv[1],"3 15 1\n"); + android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume); + assert(sink.real_volume.value==3*PA_VOLUME_NORM/15 && sink.muted && sink.n_volume_steps==16); + assert(sink.soft_volume.value==PA_VOLUME_NORM && restarts==2); + sink.real_volume.value=2*PA_VOLUME_NORM/3; sink.set_volume(&sink); + char *request=pa_sprintf_malloc("%s/volume.request",argv[1]); + FILE *f=fopen(request,"r"); unsigned level; assert(f && fscanf(f,"%u",&level)==1 && level==10); fclose(f); free(request); + android_volume_free(userdata.android_volume); assert(frees==1); + return 0; +} +''' + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "pulsecore").mkdir() + for name in ("core-rtclock.h", "core-subscribe.h"): + (root / "pulsecore" / name).touch() + source = root / "test.c" + source.write_text(harness) + binary = root / "test" + subprocess.run(["cc", "-std=c11", "-I", str(root), "-I", str(header.parent), + str(source), "-o", str(binary)], check=True, capture_output=True) + subprocess.run([str(binary), str(root)], check=True, capture_output=True) diff --git a/tools/tests/test_device_controls.py b/tools/tests/test_device_controls.py new file mode 100644 index 0000000000..091d29a5a5 --- /dev/null +++ b/tools/tests/test_device_controls.py @@ -0,0 +1,171 @@ +import json +from pathlib import Path +import runpy +import subprocess +import tempfile +import unittest +from unittest import mock + +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat")) + + +class DeviceControlsTest(unittest.TestCase): + def test_sync_controls_queued_notifications_are_processed_without_another_frame(self): + with tempfile.TemporaryDirectory() as directory: + Path(directory, "state.json").write_text(json.dumps({"brightness": 0.5, "revision": 1})) + helper = LIVE["Helper"]("/steam", 0) + helper.controls_installed = True + page = mock.Mock(events=[]) + page.ws.pending.return_value = False + helper.page = page + payload = json.dumps({"id": 1, "options": {"strTitle": "Pick a file"}}) + def evaluate(expression): + for name, value in [(LIVE["BRIGHTNESS_BINDING"], "0.4"), (LIVE["FILE_BINDING"], payload)]: + page.events.append({"method": "Runtime.bindingCalled", "params": {"name": name, "payload": value}}) + return True + def drain(): + events, page.events = page.events, [] + return events + page.evaluate.side_effect = evaluate + page.drain.side_effect = drain + helper.reconcile = mock.Mock() + helper.ensure_tools = mock.Mock(side_effect=[None, StopIteration]) + helper.open_chooser = mock.Mock() + watcher = mock.Mock() + watcher.fileno.return_value = -1 + watcher.changed.return_value = False + globals_ = LIVE["Helper"].serve.__globals__ + with mock.patch.dict(globals_, {"CONTROLS_DIR": directory, + "brightness_request": lambda value: LIVE["brightness_request"](value, directory)}), \ + mock.patch.dict(globals_["COMPAT"], {"state_path": lambda name: str(Path(directory, name))}), \ + mock.patch.object(globals_["select"], "select", return_value=([], [], [])) as select_: + with self.assertRaises(StopIteration): + helper.serve(watcher) + self.assertEqual(float(Path(directory, "brightness.request").read_text()), 0.4) + helper.open_chooser.assert_called_once_with(payload) + self.assertEqual(page.events, []) + select_.assert_not_called() + + def test_native_brightness_notifications_do_not_echo_android_readback(self): + harness = r""" +const assert = require('assert'); +globalThis.window = globalThis; +const requests = [], callbacks = []; +const timers = []; +globalThis.setTimeout = callback => timers.push(callback); +let current = 1; +window.droiddeckBrightnessChanged = value => requests.push(Number(value)); +globalThis.SteamClient = { System: { Display: { + RegisterForBrightnessChanges(cb) { callbacks.push(cb); cb({ flBrightness: 1 }); return {}; }, + SetBrightness(value) { + if (current === value) return; + current = value; + callbacks.forEach(cb => cb({ flBrightness: value })); + } +} } }; +const script = require('fs').readFileSync(process.argv[2], 'utf8'); +assert.strictEqual(eval(script), 'installed'); +assert.strictEqual(eval(script), 'present'); +const bridge = window.__droiddeckBrightness; +bridge.set(0.5); +bridge.set(0.5); +assert.deepStrictEqual(requests, []); +callbacks.forEach(cb => cb({ flBrightness: 0.8 })); +assert.deepStrictEqual(requests, [0.8]); +bridge.set(0.7992126); +assert.deepStrictEqual(requests, [0.8]); +for (const value of [NaN, Infinity, -1, 2, '0.5']) callbacks.forEach(cb => cb({ flBrightness: value })); +assert.deepStrictEqual(requests, [0.8]); +assert.strictEqual(callbacks.length, 1); +SteamClient.System.Display.SetBrightness = value => callbacks.forEach(cb => cb({ flBrightness: value + 0.1 })); +bridge.set(0.3); +assert.deepStrictEqual(requests, [0.8]); +callbacks.forEach(cb => cb({ flBrightness: 0.6 })); +assert.deepStrictEqual(requests, [0.8, 0.6]); +SteamClient.System.Display.SetBrightness = () => {}; +bridge.set(0.65); +timers.forEach(callback => callback()); +callbacks.forEach(cb => cb({ flBrightness: 0.7 })); +assert.deepStrictEqual(requests, [0.8, 0.6, 0.7]); +""" + with tempfile.TemporaryDirectory() as directory: + script = Path(directory) / "bridge.js" + script.write_text(LIVE["BRIGHTNESS_JS"]) + test = Path(directory) / "test.js" + test.write_text(harness) + result = subprocess.run(["node", str(test), str(script)], capture_output=True, text=True, timeout=20) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_requests_reject_nonfinite_and_out_of_range_values(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "brightness.request" + for value in ["NaN", "Infinity", "-0.1", "1.1", "invalid", None]: + LIVE["brightness_request"](value, directory) + self.assertFalse(path.exists()) + LIVE["brightness_request"]("0.4", directory) + self.assertEqual(float(path.read_text()), 0.4) + + def test_failed_request_revision_republishes_the_actual_brightness(self): + with tempfile.TemporaryDirectory() as directory: + globals_ = LIVE["Helper"].sync_controls.__globals__ + previous = globals_["CONTROLS_DIR"] + try: + globals_["CONTROLS_DIR"] = directory + helper = LIVE["Helper"]("/steam", 0) + calls = [] + helper.controls_installed = True + helper.page = type("Page", (), {"evaluate": lambda self, expression: calls.append(expression) or True})() + path = Path(directory) / "state.json" + path.write_text(json.dumps({"brightness": 0.5, "revision": 1})) + helper.sync_controls() + helper.sync_controls() + self.assertEqual(len(calls), 1) + path.write_text(json.dumps({"brightness": 0.5, "revision": 2})) + helper.sync_controls() + self.assertEqual(len(calls), 2) + finally: + globals_["CONTROLS_DIR"] = previous + + def test_display_bridge_retries_binding_and_install_before_caching_state(self): + with tempfile.TemporaryDirectory() as directory: + globals_ = LIVE["Helper"].sync_controls.__globals__ + previous = globals_["CONTROLS_DIR"] + try: + globals_["CONTROLS_DIR"] = directory + Path(directory, "state.json").write_text(json.dumps({"brightness": 0.5, "revision": 1})) + calls, installs, writes = [], ["unavailable", "installed", "present"], [] + class Page: + present = True + def call(self, method, params): + calls.append((method, params)) + def evaluate(self, expression): + if expression == LIVE["BRIGHTNESS_JS"]: + return installs.pop(0) + writes.append(expression) + return self.present + helper = LIVE["Helper"]("/steam", 0) + helper.page = Page() + helper.sync_controls() + self.assertIsNone(helper.controls_state) + self.assertFalse(writes) + helper.sync_controls() + helper.sync_controls() + self.assertEqual(len(calls), 2) + self.assertEqual(len(writes), 1) + self.assertEqual(calls[1], ("Runtime.addBinding", {"name": LIVE["BRIGHTNESS_BINDING"]})) + helper.page.present = False + Path(directory, "state.json").write_text(json.dumps({"brightness": 0.7, "revision": 2})) + helper.sync_controls() + self.assertIsNone(helper.controls_state) + self.assertFalse(helper.controls_installed) + helper.page.present = True + helper.sync_controls() + self.assertEqual(len(calls), 3) + self.assertEqual(helper.controls_state["brightness"], 0.7) + finally: + globals_["CONTROLS_DIR"] = previous + + +if __name__ == "__main__": + unittest.main()