Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

feat(android): phone volume buttons control a playing PC

Bee7880c0b1ed41
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1665bd7..c44da62 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -106,6 +106,10 @@ has a Stop button. Choosing another
Home (**Stop reconnecting** while it isn't connected) keeps a phone or PC
disconnected, even after a restart, until you tap **Reconnect**
([#48](https://github.com/thtbee/nectarlink/issues/48)).
+- **The phone's volume buttons control your PC** while it plays music or
+ video, in 4% steps, as with KDE Connect. When the phone plays something
+ itself, or the PC is paused, they work on the phone as usual. Turn it off
+ in the phone's **Settings › Control your PC**.
### Changed
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
index 4b38285..10c7184 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
@@ -199,9 +199,10 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
val pcMedia = PcMedia(
context = this.context,
onSeedColorChanged = { syncActiveMediaColor() },
+ setPcAudio = { pc, volume, muted -> setPcAudio(pc, volume, muted) },
) { pc, player, action, position ->
command { it.mediaCommand(pc, player, action, position) }
- }
+ }.also { it.volumeKeys(app.nectarlink.android.ui.Preferences.isVolumeKeysControlPcEnabled(this.context)) }
private fun syncActiveMediaColor() {
val nextColor = phoneMedia.activeSeedColor ?: pcMedia.activeSeedColor
@@ -477,6 +478,18 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
app.nectarlink.android.widget.PcWidgetProvider.refreshAll(context, s)
}
}
+ currentRunScope.launch(Dispatchers.Default) {
+ // The volume buttons reach a PC whose volume this phone may set.
+ _state
+ .map { s ->
+ s.devices
+ .filter { it.online && it.has("media.pc_audio") }
+ .mapNotNull { d -> d.deckState?.let { d.id to PcMedia.PcLevel(it.volume.toInt(), it.muted) } }
+ .toMap()
+ }
+ .distinctUntilChanged()
+ .collect { pcMedia.levels(it) }
+ }
currentRunScope.launch(Dispatchers.IO) {
var first = true
_state
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/media/PcMedia.kt b/android/app/src/main/kotlin/app/nectarlink/android/media/PcMedia.kt
index acb7d6e..e879216 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/media/PcMedia.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/media/PcMedia.kt
@@ -13,7 +13,10 @@ import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Icon
+import android.media.AudioAttributes
+import android.media.AudioManager
import android.media.MediaMetadata
+import android.media.VolumeProvider
import android.media.session.MediaSession
import android.media.session.PlaybackState
import android.os.Handler
@@ -32,11 +35,16 @@ import app.nectarlink.core.MediaPlayer
* stands for the PC's player, and its notification. What the user presses
* goes to the PC through [send]; the PC's new state comes back as an update.
*
+ * While a PC player plays and [volumeKeys] is on, the session's volume is
+ * the PC's: Android then sends the phone's volume buttons to it (unless
+ * the phone plays something itself), and [setPcAudio] passes them on.
+ *
* Everything runs on the main thread.
*/
class PcMedia(
context: Context,
private val onSeedColorChanged: () -> Unit = {},
+ private val setPcAudio: (pc: String, volume: Int?, muted: Boolean?) -> Unit = { _, _, _ -> },
private val send: (pc: String, player: String, action: MediaAction, position: ULong?) -> Unit,
) {
private val context = context.applicationContext
@@ -101,6 +109,15 @@ class PcMedia(
private var session: MediaSession? = null
private var shown: Pair<String, MediaPlayer>? = null
+
+ /** Each PC's master volume, for the PCs whose volume this phone may set. */
+ private var levels: Map<String, PcLevel> = emptyMap()
+ private var volumeKeys = true
+ /** The PC the session's volume stands for, while it does. */
+ private var remote: PcVolume? = null
+
+ /** A PC's master volume (`0..=100`) and mute. */
+ data class PcLevel(val volume: Int, val muted: Boolean)
private val stalePauseTimeout = Runnable { hide() }
private val callback = object : MediaSession.Callback() {
@@ -144,6 +161,20 @@ class PcMedia(
}
}
+ /** The volume of each PC this phone may set (from its deck state). */
+ fun levels(levels: Map<String, PcLevel>) = main.post {
+ if (levels == this.levels) return@post
+ this.levels = levels
+ session?.let { route(it) }
+ }
+
+ /** Whether the volume buttons may set a playing PC's volume (Settings). */
+ fun volumeKeys(enabled: Boolean) = main.post {
+ if (enabled == volumeKeys) return@post
+ volumeKeys = enabled
+ session?.let { route(it) }
+ }
+
/** Asks the PC [pc]'s [player] to [action] (Play on phone's controls). */
fun command(pc: String, player: String, action: MediaAction) = send(pc, player, action, null)
@@ -238,6 +269,7 @@ class PcMedia(
)
.build(),
)
+ route(session)
session.isActive = true
post(notification(session, player, cleanTitle, subtitleLine, picture))
if (!player.playing) {
@@ -248,9 +280,71 @@ class PcMedia(
}
}
+ /**
+ * Gives the session the shown PC's volume while that PC plays and its
+ * volume is known, and the phone's media volume otherwise.
+ */
+ private fun route(session: MediaSession) {
+ val (pc, player) = shown ?: return
+ val level = levels[pc]?.takeIf { volumeKeys && player.playing }
+ if (level == null) {
+ if (remote != null) {
+ remote = null
+ session.setPlaybackToLocal(
+ AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).build(),
+ )
+ }
+ return
+ }
+ val current = remote
+ if (current != null && current.pc == pc) {
+ current.show(level)
+ return
+ }
+ remote = PcVolume(pc, level).also(session::setPlaybackToRemote)
+ }
+
+ /** The PC [pc]'s master volume as Android's volume controls see it, in [VOLUME_STEPS]. */
+ private inner class PcVolume(val pc: String, private var level: PcLevel) :
+ VolumeProvider(VOLUME_CONTROL_ABSOLUTE, VOLUME_STEPS, toSteps(level.volume)) {
+
+ fun show(level: PcLevel) {
+ this.level = level
+ currentVolume = toSteps(level.volume)
+ }
+
+ override fun onSetVolumeTo(volume: Int) {
+ main.post { set(volume.coerceIn(0, VOLUME_STEPS), null) }
+ }
+
+ override fun onAdjustVolume(direction: Int) {
+ main.post {
+ when (direction) {
+ AudioManager.ADJUST_TOGGLE_MUTE -> set(null, !level.muted)
+ AudioManager.ADJUST_MUTE -> set(null, true)
+ AudioManager.ADJUST_UNMUTE -> set(null, false)
+ AudioManager.ADJUST_SAME -> {}
+ // Turning it up unmutes it, as the PC's own keys do.
+ else -> set(
+ (currentVolume + direction.coerceIn(-1, 1)).coerceIn(0, VOLUME_STEPS),
+ if (direction > 0 && level.muted) false else null,
+ )
+ }
+ }
+ }
+
+ private fun set(steps: Int?, muted: Boolean?) {
+ if (remote !== this) return
+ val volume = steps?.let { it * 100 / VOLUME_STEPS }
+ show(PcLevel(volume ?: level.volume, muted ?: level.muted))
+ setPcAudio(pc, volume, muted)
+ }
+ }
+
private fun hide() {
main.removeCallbacks(stalePauseTimeout)
shown = null
+ remote = null
val hadSummary = currentSummary != null
currentSummary = null
if (activeSeedColor != null) {
@@ -343,6 +437,12 @@ class PcMedia(
private const val NOTIFICATION_ID = 1
const val EXTRA_ACTION = "action"
+ /** Steps of the PC's volume on the phone: each button press moves it 4%. */
+ internal const val VOLUME_STEPS = 25
+
+ /** A PC volume (`0..=100`) as the nearest step. */
+ internal fun toSteps(volume: Int): Int = ((volume.coerceIn(0, 100) * VOLUME_STEPS + 50) / 100)
+
private fun isOpaqueHexOrAumid(s: String): Boolean {
val trimmed = s.trim()
if (trimmed.isEmpty()) return true
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
index f65cc88..994dea7 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
@@ -783,6 +783,7 @@ private fun App(
val recorderSession by recorderFlow.collectAsStateWithLifecycle(recorderInitial)
val touchpadSensitivity by preferences.touchpadSensitivity.collectAsStateWithLifecycle()
val suggestClipboardActions by preferences.suggestClipboardActions.collectAsStateWithLifecycle()
+ val volumeKeysControlPc by preferences.volumeKeysControlPc.collectAsStateWithLifecycle()
val backgroundServiceEnabled by preferences.backgroundServiceEnabled.collectAsStateWithLifecycle()
val hiveInviteShown by preferences.hiveInviteShown.collectAsStateWithLifecycle()
val saveableStateHolder = androidx.compose.runtime.saveable.rememberSaveableStateHolder()
@@ -951,6 +952,8 @@ private fun App(
onClearClipboardHistory = core::clearClipboardHistory,
suggestClipboardActions = suggestClipboardActions,
onSetSuggestClipboardActions = preferences::updateSuggestClipboardActions,
+ volumeKeysControlPc = volumeKeysControlPc,
+ onSetVolumeKeysControlPc = preferences::updateVolumeKeysControlPc,
backgroundServiceEnabled = backgroundServiceEnabled,
onToggleBackgroundService = { enabled ->
preferences.updateBackgroundServiceEnabled(enabled)
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/Preferences.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/Preferences.kt
index 4fa5a81..689e6df 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/Preferences.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/Preferences.kt
@@ -24,6 +24,9 @@ class Preferences(context: Context) {
private val _suggestClipboardActions = MutableStateFlow(prefs.getBoolean(SUGGEST_CLIPBOARD_ACTIONS, true))
val suggestClipboardActions: StateFlow<Boolean> = _suggestClipboardActions.asStateFlow()
+ private val _volumeKeysControlPc = MutableStateFlow(prefs.getBoolean(VOLUME_KEYS_CONTROL_PC, true))
+ val volumeKeysControlPc: StateFlow<Boolean> = _volumeKeysControlPc.asStateFlow()
+
private val _backgroundServiceEnabled = MutableStateFlow(prefs.getBoolean(BACKGROUND_SERVICE_ENABLED, true))
val backgroundServiceEnabled: StateFlow<Boolean> = _backgroundServiceEnabled.asStateFlow()
@@ -107,6 +110,12 @@ class Preferences(context: Context) {
}
}
+ fun updateVolumeKeysControlPc(enabled: Boolean) {
+ prefs.edit { putBoolean(VOLUME_KEYS_CONTROL_PC, enabled) }
+ _volumeKeysControlPc.value = enabled
+ (appContext as app.nectarlink.android.NectarlinkApplication).core.pcMedia.volumeKeys(enabled)
+ }
+
fun updateBackgroundServiceEnabled(enabled: Boolean) {
prefs.edit { putBoolean(BACKGROUND_SERVICE_ENABLED, enabled) }
_backgroundServiceEnabled.value = enabled
@@ -138,6 +147,7 @@ class Preferences(context: Context) {
private const val HIVE_INVITE_ANSWERED = "hive_invite_answered_version"
private const val TOUCHPAD_SENSITIVITY = "touchpad_sensitivity"
private const val SUGGEST_CLIPBOARD_ACTIONS = "suggest_clipboard_actions"
+ private const val VOLUME_KEYS_CONTROL_PC = "volume_keys_control_pc"
internal const val BACKGROUND_SERVICE_ENABLED = "background_service_enabled"
private const val AWAY_MODE = "away_mode"
private const val WALKTHROUGH_COMPLETED = "walkthrough_completed"
@@ -184,6 +194,11 @@ class Preferences(context: Context) {
.getSharedPreferences("appearance", Context.MODE_PRIVATE)
.getBoolean(SUGGEST_CLIPBOARD_ACTIONS, true)
+ fun isVolumeKeysControlPcEnabled(context: Context): Boolean =
+ context.applicationContext
+ .getSharedPreferences("appearance", Context.MODE_PRIVATE)
+ .getBoolean(VOLUME_KEYS_CONTROL_PC, true)
+
fun isAwayModeEnabled(context: Context): Boolean =
context.applicationContext
.getSharedPreferences("appearance", Context.MODE_PRIVATE)
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
index b271cd3..dde793c 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
@@ -114,6 +114,8 @@ fun SettingsScreen(
onClearClipboardHistory: () -> Unit = {},
suggestClipboardActions: Boolean = true,
onSetSuggestClipboardActions: (Boolean) -> Unit = {},
+ volumeKeysControlPc: Boolean = true,
+ onSetVolumeKeysControlPc: (Boolean) -> Unit = {},
backgroundServiceEnabled: Boolean = true,
onToggleBackgroundService: (Boolean) -> Unit = {},
onSetTimelineRetentionDays: (UInt) -> Unit = {},
@@ -758,6 +760,24 @@ fun SettingsScreen(
valueRange = 0.5f..2.5f,
modifier = Modifier.semantics { contentDescription = sensitivityTitle },
)
+ SettingRowDivider()
+ val volumeKeysTitle = stringResource(R.string.settings_volume_keys_control_pc)
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Column(Modifier.weight(1f).padding(end = 12.dp)) {
+ Text(volumeKeysTitle, style = MaterialTheme.typography.titleSmall)
+ Text(
+ stringResource(R.string.settings_volume_keys_control_pc_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ Switch(
+ checked = volumeKeysControlPc,
+ onCheckedChange = onSetVolumeKeysControlPc,
+ colors = app.nectarlink.android.ui.theme.nectarSwitchColors(),
+ modifier = Modifier.semantics { contentDescription = volumeKeysTitle },
+ )
+ }
}
}
diff --git a/android/app/src/main/res/values-de/strings.xml b/android/app/src/main/res/values-de/strings.xml
index 00a8931..0479e99 100644
--- a/android/app/src/main/res/values-de/strings.xml
+++ b/android/app/src/main/res/values-de/strings.xml
@@ -324,6 +324,8 @@
<string name="action_remote_pc">PC steuern</string>
<string name="action_back">Zurück</string>
<string name="settings_remote">Deinen PC steuern</string>
+ <string name="settings_volume_keys_control_pc">Lautstärketasten steuern den PC</string>
+ <string name="settings_volume_keys_control_pc_hint">Während auf dem PC Musik oder ein Video läuft, ändern die Lautstärketasten des Smartphones die Lautstärke des PCs.</string>
<string name="settings_touchpad_sensitivity">Touchpad-Geschwindigkeit</string>
<string name="settings_touchpad_sensitivity_value">%1$.1f×</string>
<string name="remote_mode_touchpad">Touchpad</string>
diff --git a/android/app/src/main/res/values-zh-rCN/strings.xml b/android/app/src/main/res/values-zh-rCN/strings.xml
index 193b893..eb79284 100644
--- a/android/app/src/main/res/values-zh-rCN/strings.xml
+++ b/android/app/src/main/res/values-zh-rCN/strings.xml
@@ -311,6 +311,8 @@
<string name="action_remote_pc">控制电脑</string>
<string name="action_back">返回</string>
<string name="settings_remote">控制你的电脑</string>
+ <string name="settings_volume_keys_control_pc">音量键控制电脑</string>
+ <string name="settings_volume_keys_control_pc_hint">电脑播放音乐或视频时,手机的音量键会调节电脑的音量。</string>
<string name="settings_touchpad_sensitivity">触控板速度</string>
<string name="settings_touchpad_sensitivity_value">%1$.1f×</string>
<string name="remote_mode_touchpad">触控板</string>
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index 4ea3153..6593d69 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -324,6 +324,8 @@
<string name="action_remote_pc">Control PC</string>
<string name="action_back">Back</string>
<string name="settings_remote">Control your PC</string>
+ <string name="settings_volume_keys_control_pc">Volume buttons control your PC</string>
+ <string name="settings_volume_keys_control_pc_hint">While your PC plays music or video, your phone\'s volume buttons change the PC\'s volume.</string>
<string name="settings_touchpad_sensitivity">Touchpad speed</string>
<string name="settings_touchpad_sensitivity_value">%1$.1f×</string>
<string name="remote_mode_touchpad">Touchpad</string>
diff --git a/android/app/src/test/kotlin/app/nectarlink/android/media/PcVolumeStepsTest.kt b/android/app/src/test/kotlin/app/nectarlink/android/media/PcVolumeStepsTest.kt
new file mode 100644
index 0000000..cb7d3c9
--- /dev/null
+++ b/android/app/src/test/kotlin/app/nectarlink/android/media/PcVolumeStepsTest.kt
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.media
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class PcVolumeStepsTest {
+ @Test
+ fun pcVolumeRoundsToTheNearestStep() {
+ assertEquals(0, PcMedia.toSteps(0))
+ assertEquals(0, PcMedia.toSteps(1))
+ assertEquals(1, PcMedia.toSteps(2))
+ assertEquals(9, PcMedia.toSteps(37))
+ assertEquals(PcMedia.VOLUME_STEPS, PcMedia.toSteps(100))
+ }
+
+ @Test
+ fun outOfRangeVolumesAreClamped() {
+ assertEquals(0, PcMedia.toSteps(-5))
+ assertEquals(PcMedia.VOLUME_STEPS, PcMedia.toSteps(140))
+ }
+
+ @Test
+ fun everyStepMapsBackToItself() {
+ for (step in 0..PcMedia.VOLUME_STEPS) {
+ assertEquals(step, PcMedia.toSteps(step * 100 / PcMedia.VOLUME_STEPS))
+ }
+ }
+}