Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Phone controls on the PC: Do Not Disturb, ringer, flashlight, volume and more
Bee8f095ddf6e7d
diff --git a/README.md b/README.mdindex ecec1e6..2d55fbd 100644--- a/README.md+++ b/README.md@@ -147,6 +147,14 @@ tests; there are no releases yet.file beside it when you add markers and a notification to open the recordingor its folder. If the PC is offline, the recording waits on the phone andgoes out as soon as it reconnects.+- **Phone controls on the PC**: see and change the phone's Do Not Disturb,+ ringer mode (Ring, Vibrate, Silent), flashlight, media volume, screen+ brightness, Wi‑Fi (with a confirmation before turning it off) and Bluetooth+ from the PC's Home screen. Volume, Ring/Vibrate and the+ flashlight work out of the box; Do Not Disturb and silent mode use+ Notification Policy Access; screen brightness uses Modify system settings;+ and Wi‑Fi and Bluetooth unlock with Wireless debugging (which also+ grants the Do Not Disturb and brightness permissions automatically).- **Media** both ways: what plays on the phone shows on the PC, in the app andin Windows' own media flyout (so the keyboard's media keys work too), andwhat plays on the PC shows in the phone's media controls, with artwork anddiff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 7038fd1..62b7b34 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -27,6 +27,12 @@<uses-permissionandroid:name="android.permission.WRITE_SECURE_SETTINGS"tools:ignore="ProtectedPermissions" />+ <!-- Quick settings from a PC: Do Not Disturb / silent mode, and screen+ brightness (asked for in Settings, or granted at Elevated). -->+ <uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />+ <uses-permission+ android:name="android.permission.WRITE_SETTINGS"+ tools:ignore="ProtectedPermissions" /><uses-permission android:name="android.permission.POST_NOTIFICATIONS" /><!-- Scanning the pairing QR code. --><uses-permission android:name="android.permission.CAMERA" />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.ktindex e42df9a..336c00d 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@@ -30,6 +30,7 @@ import app.nectarlink.android.recorder.RecordingsStoreimport app.nectarlink.android.recorder.SavedRecordingimport app.nectarlink.android.service.ConnectionServiceimport app.nectarlink.android.sms.PhoneSms+import app.nectarlink.android.toggles.PhoneTogglesimport app.nectarlink.core.Eventimport app.nectarlink.core.EventListenerimport app.nectarlink.core.FileToSend@@ -81,11 +82,21 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenercalls = { calls },contacts = { contacts },sms = { sms },+ toggles = { toggles },onMirror = { pc, request ->MirrorRequests.show(this.context, request, _state.value.nameOf(pc).orEmpty())},appWindows = AppWindows(this.context, scope, open = { pc -> mirrorOpen(pc) }, nameOf = { pc -> _state.value.nameOf(pc).orEmpty() }),)+ private val toggles = PhoneToggles(+ this.context,+ onChanged = { state ->+ notificationOps.trySend { node ->+ runCatching { node.togglesChanged(state) }.onFailure { Log.i(TAG, "toggles weren't reported", it) }+ }+ },+ onCapabilitiesChanged = { refreshNotificationAccess() },+ )private val sms = PhoneSms(this.context) {notificationOps.trySend { it.smsChanged(null) }}@@ -198,12 +209,15 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenercallAccess = PhoneCalls.hasAll(context),contactsAccess = PhoneContacts.canRead(context),smsAccess = PhoneSms.hasAll(context),+ dndAccess = PhoneToggles.hasDndAccess(context),+ writeSettingsAccess = PhoneToggles.hasWriteSettings(context),)}started.updatePower(powerLevel(), capabilities(NotificationListener.hasAccess(context)))// Elevated, when set up and wireless debugging is on.scope.launch { Elevated.start() }scope.launch(Dispatchers.Main) {+ toggles.start()if (_state.value.photoAccess) photos.start()if (PhoneCalls.canFollow(context) || PhoneCalls.canReadLog(context)) calls.start()if (PhoneContacts.canRead(context)) contacts.start()@@ -261,6 +275,8 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerval smsAccess = PhoneSms.hasAll(context)val inputAccess = InputService.runningval elevated = Elevated.running+ val dndAccess = PhoneToggles.hasDndAccess(context)+ val writeSettingsAccess = PhoneToggles.hasWriteSettings(context)val localNetwork = LocalNetwork.granted(context)if (localNetwork && !_state.value.localNetwork) {// Just allowed: reach the PCs now rather than at the next retry.@@ -278,6 +294,8 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenersmsAccess = smsAccess,inputAccess = inputAccess,elevated = elevated,+ dndAccess = dndAccess,+ writeSettingsAccess = writeSettingsAccess,localNetwork = localNetwork,)}@@ -286,6 +304,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener}if (node != null) {scope.launch(Dispatchers.Main) {+ toggles.start()if (photoAccess) photos.start() else photos.stop()if (PhoneCalls.canFollow(context) || PhoneCalls.canReadLog(context)) calls.start() else calls.stop()if (contactsAccess) contacts.start() else contacts.stop()@@ -537,6 +556,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener/** What this phone offers PCs (docs/protocol/capabilities.md). */private fun capabilities(notificationAccess: Boolean): List<String> =CLIPBOARD_CAPABILITIES ++ toggles.capabilities() +(if (notificationAccess) NOTIFICATION_CAPABILITIES + MEDIA_CAPABILITIES else emptyList()) +(if (_state.value.photoAccess) PHOTO_CAPABILITIES else emptyList()) +(if (PhoneCalls.canFollow(context)) listOf("call.state") else emptyList()) +diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.ktindex c739012..a14e4e8 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt@@ -80,6 +80,10 @@ data class CoreState(val photoPartialAccess: Boolean = false,/** Whether Android lets Nectarlink run unrestricted in the background. */val backgroundUnrestricted: Boolean = true,+ /** Whether the user allowed Do Not Disturb / silent mode control from a PC. */+ val dndAccess: Boolean = false,+ /** Whether the user allowed screen brightness changes from a PC. */+ val writeSettingsAccess: Boolean = false,/** File transfers, newest first (running ones and the latest finished). */val transfers: List<Transfer> = emptyList(),) {@@ -124,13 +128,14 @@ data class CoreState(is Event.Transfer -> copy(transfers = withTransfer(event.transfer))// Shown in Android's media controls (see media/PcMedia).is Event.MediaChanged -> this- // PCs only: phones announce their own photos, calls, contacts, texts and screen.+ // PCs only: phones announce their own photos, calls, contacts, texts, toggles and screen.is Event.PhotoAdded,is Event.PhotosChanged,is Event.CallChanged,is Event.CallLogChanged,is Event.ContactsChanged,is Event.SmsChanged,+ is Event.PhoneToggles,is Event.Mirroring,is Event.RemoteInputRequested,-> thisdiff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.ktindex 3147b40..4a07fa6 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt@@ -21,6 +21,7 @@ import app.nectarlink.android.mirror.MirrorRequestimport app.nectarlink.android.mirror.MirrorRequestsimport app.nectarlink.android.mirror.MirrorServiceimport app.nectarlink.android.sms.PhoneSms+import app.nectarlink.android.toggles.PhoneTogglesimport app.nectarlink.core.CallCommandimport app.nectarlink.core.CallLogEntryimport app.nectarlink.core.Contact@@ -32,6 +33,7 @@ import app.nectarlink.core.MediaActionimport app.nectarlink.core.MirrorInputEventimport app.nectarlink.core.MirrorOptionsimport app.nectarlink.core.PhoneApp+import app.nectarlink.core.PhoneToggleValueimport app.nectarlink.core.PhotoAlbumimport app.nectarlink.core.PhotoItemimport app.nectarlink.core.PhotoThumb@@ -54,6 +56,8 @@ internal class PhonePlatform(private val contacts: () -> PhoneContacts,/** The phone's texts (created after this). */private val sms: () -> PhoneSms,+ /** The phone's quick settings (created after this). */+ private val toggles: () -> PhoneToggles,/** Asks the user to share the screen with a PC: (PC's ID, request) → asked. */private val onMirror: (String, MirrorRequest) -> Boolean,/** Apps in windows of their own on PCs (Elevated). */@@ -132,6 +136,9 @@ internal class PhonePlatform(override fun smsPart(id: String): SmsPartData? = sms().part(id)+ override fun setPhoneToggle(id: String, value: PhoneToggleValue): Boolean =+ toggles().set(id, value)+override fun dismissNotification(key: String) {val listener = NotificationListener.instance ?: throw NotificationFailure.Unsupported()listener.dismiss(key)diff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.ktindex 74d9ee9..08bf900 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt@@ -190,6 +190,13 @@ object Elevated {if (!CallCompanion.allowed(context) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {run(adb, "appops set ${context.packageName} ${CallCompanion.OP_NAME} allow")}+ // Lets PCs toggle Do Not Disturb / silent mode and screen brightness without extra prompts.+ if (context.getSystemService(android.app.NotificationManager::class.java)?.isNotificationPolicyAccessGranted == false) {+ run(adb, "cmd notification allow_dnd ${context.packageName}")+ }+ if (!Settings.System.canWrite(context)) {+ run(adb, "appops set ${context.packageName} WRITE_SETTINGS allow")+ }val token = ByteArray(24).also(SecureRandom()::nextBytes).joinToString("") { "%02x".format(it) }val apk = context.applicationInfo.sourceDirval command = "CLASSPATH=$apk app_process /system/bin ${InputServer::class.java.name} $token"@@ -302,6 +309,12 @@ object Elevated {return send(writer, line)}+ /** Runs an allowed shell command through the Elevated helper. */+ fun runCommand(command: String): Boolean {+ val writer = input ?: return false+ return send(writer, "C $command")+ }+/*** Opens an app window: the helper runs [pkg] on a display of its own of* [width] × [height] pixels at [dpi], and streams it on the returneddiff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.ktindex 160ccba..e02a417 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt@@ -186,7 +186,9 @@ object InputServer {}"K" -> key(rest.toInt())"T" -> type(rest)- "C" -> if (rest in allowed && display < 0) Runtime.getRuntime().exec(rest.split(' ').toTypedArray()).waitFor()+ "C" -> if (allowedCommand(rest) && display < 0) {+ Runtime.getRuntime().exec(rest.split(' ').toTypedArray()).waitFor()+ }}}@@ -243,7 +245,26 @@ object InputServer {}}+ private fun allowedCommand(cmd: String): Boolean {+ if (cmd in allowed) return true+ if (cmd.startsWith(BRIGHTNESS_PREFIX)) {+ val v = cmd.removePrefix(BRIGHTNESS_PREFIX).toIntOrNull()+ return v != null && v in 0..255+ }+ return false+ }+/** The only shell commands the app may run through this. */- private val allowed = setOf("cmd statusbar expand-notifications")+ private val allowed = setOf(+ "cmd statusbar expand-notifications",+ "svc wifi enable",+ "svc wifi disable",+ "svc bluetooth enable",+ "svc bluetooth disable",+ )++ private companion object {+ const val BRIGHTNESS_PREFIX = "settings put system screen_brightness "+ }}}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/toggles/PhoneToggles.kt b/android/app/src/main/kotlin/app/nectarlink/android/toggles/PhoneToggles.ktnew file mode 100644index 0000000..611e4ca--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/toggles/PhoneToggles.kt@@ -0,0 +1,363 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.toggles++import android.app.NotificationManager+import android.bluetooth.BluetoothAdapter+import android.bluetooth.BluetoothManager+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.database.ContentObserver+import android.hardware.camera2.CameraCharacteristics+import android.hardware.camera2.CameraManager+import android.media.AudioManager+import android.net.Uri+import android.net.wifi.WifiManager+import android.os.Build+import android.os.Handler+import android.os.Looper+import android.provider.Settings+import android.util.Log+import androidx.core.content.ContextCompat+import app.nectarlink.android.elevated.Elevated+import app.nectarlink.core.PhoneToggleValue+import app.nectarlink.core.PhoneToggles as CorePhoneToggles+import kotlin.math.roundToInt++/**+ * Reads, watches, and changes the phone's quick settings for paired PCs+ * (`docs/protocol/toggles.md`).+ */+class PhoneToggles(+ context: Context,+ private val onChanged: (CorePhoneToggles) -> Unit,+ private val onCapabilitiesChanged: () -> Unit,+) {+ private val context = context.applicationContext+ private val mainHandler = Handler(Looper.getMainLooper())+ private val audio = this.context.getSystemService(AudioManager::class.java)+ private val notifications = this.context.getSystemService(NotificationManager::class.java)+ private val camera = this.context.getSystemService(CameraManager::class.java)+ private val wifi = this.context.getSystemService(WifiManager::class.java)+ private val bluetooth = this.context.getSystemService(BluetoothManager::class.java)++ private val torchCameraId: String? = findTorchCamera()+ @Volatile private var torchOn: Boolean = false+ private var started = false+ private var lastSent: CorePhoneToggles? = null++ private val emitRunnable = Runnable { pushIfChanged() }+ private val followUpRunnable = Runnable { pushIfChanged() }++ private val torchCallback = object : CameraManager.TorchCallback() {+ override fun onTorchModeChanged(cameraId: String, enabled: Boolean) {+ if (cameraId == torchCameraId && torchOn != enabled) {+ torchOn = enabled+ schedulePush()+ }+ }+ }++ private val settingsObserver = object : ContentObserver(mainHandler) {+ override fun onChange(selfChange: Boolean) {+ schedulePush()+ }+ }++ private val receiver = object : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ if (intent.action == NotificationManager.ACTION_NOTIFICATION_POLICY_ACCESS_GRANTED_CHANGED) {+ onCapabilitiesChanged()+ }+ schedulePush()+ }+ }++ fun start() {+ if (started) return+ started = true+ if (torchCameraId != null) {+ runCatching { camera?.registerTorchCallback(torchCallback, mainHandler) }+ .onFailure { Log.w(TAG, "torch callback failed", it) }+ }+ runCatching {+ context.contentResolver.registerContentObserver(+ Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS),+ false,+ settingsObserver,+ )+ context.contentResolver.registerContentObserver(+ Settings.Global.getUriFor(Settings.Global.BLUETOOTH_ON),+ false,+ settingsObserver,+ )+ }.onFailure { Log.w(TAG, "settings observer failed", it) }++ val filter = IntentFilter().apply {+ addAction(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED)+ addAction(NotificationManager.ACTION_NOTIFICATION_POLICY_ACCESS_GRANTED_CHANGED)+ addAction(AudioManager.RINGER_MODE_CHANGED_ACTION)+ addAction(VOLUME_CHANGED_ACTION)+ addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)+ addAction(BluetoothAdapter.ACTION_STATE_CHANGED)+ }+ ContextCompat.registerReceiver(context, receiver, filter, ContextCompat.RECEIVER_EXPORTED)+ pushNow()+ }++ fun stop() {+ if (!started) return+ started = false+ mainHandler.removeCallbacks(emitRunnable)+ mainHandler.removeCallbacks(followUpRunnable)+ if (torchCameraId != null) {+ runCatching { camera?.unregisterTorchCallback(torchCallback) }+ }+ runCatching { context.contentResolver.unregisterContentObserver(settingsObserver) }+ runCatching { context.unregisterReceiver(receiver) }+ }++ /** What `toggles.*` capabilities this phone currently offers. */+ fun capabilities(): List<String> = buildList {+ add("toggles.read")+ add("toggles.ringer")+ add("toggles.volume")+ if (torchCameraId != null) add("toggles.flashlight")+ if (canChangeDnd(context)) add("toggles.dnd")+ if (canChangeBrightness(context)) add("toggles.brightness")+ if (Elevated.running) {+ add("toggles.wifi")+ add("toggles.bluetooth")+ }+ }++ /** Reads the current state of all phone quick settings. */+ fun snapshot(): CorePhoneToggles = CorePhoneToggles(+ dnd = readDnd(),+ ringer = readRinger(),+ flashlight = if (torchCameraId != null) torchOn else null,+ volume = readVolume().toUByte(),+ brightness = readBrightness().toUByte(),+ wifi = readWifi(),+ bluetooth = readBluetooth(),+ )++ /** Forces an immediate snapshot push to `nectarlink-core`. */+ @Synchronized+ fun pushNow() {+ val current = snapshot()+ lastSent = current+ onChanged(current)+ }++ /** Changes one quick setting on the phone (`phone.toggle.set`). */+ fun set(id: String, value: PhoneToggleValue): Boolean {+ val ok = runCatching {+ when (id) {+ "dnd" -> {+ val on = (value as? PhoneToggleValue.Bool)?.on ?: return false+ setDnd(on)+ }+ "ringer" -> {+ val mode = (value as? PhoneToggleValue.Mode)?.mode ?: return false+ setRinger(mode)+ }+ "flashlight" -> {+ val on = (value as? PhoneToggleValue.Bool)?.on ?: return false+ setFlashlight(on)+ }+ "volume" -> {+ val level = (value as? PhoneToggleValue.Level)?.level?.toInt() ?: return false+ setVolume(level)+ }+ "brightness" -> {+ val level = (value as? PhoneToggleValue.Level)?.level?.toInt() ?: return false+ setBrightness(level)+ }+ "wifi" -> {+ val on = (value as? PhoneToggleValue.Bool)?.on ?: return false+ Elevated.runCommand(if (on) "svc wifi enable" else "svc wifi disable")+ }+ "bluetooth" -> {+ val on = (value as? PhoneToggleValue.Bool)?.on ?: return false+ Elevated.runCommand(if (on) "svc bluetooth enable" else "svc bluetooth disable")+ }+ else -> false+ }+ }.onFailure { Log.w(TAG, "toggle $id failed", it) }.getOrDefault(false)+ if (ok) {+ pushIfChanged()+ schedulePush()+ mainHandler.removeCallbacks(followUpRunnable)+ mainHandler.postDelayed(followUpRunnable, FOLLOW_UP_MS)+ }+ return ok+ }++ private fun schedulePush() {+ mainHandler.removeCallbacks(emitRunnable)+ mainHandler.postDelayed(emitRunnable, DEBOUNCE_MS)+ }++ @Synchronized+ private fun pushIfChanged() {+ val current = snapshot()+ if (current != lastSent) {+ lastSent = current+ onChanged(current)+ }+ }++ private fun readDnd(): Boolean {+ val filter = notifications?.currentInterruptionFilter ?: return false+ return filter != NotificationManager.INTERRUPTION_FILTER_ALL &&+ filter != NotificationManager.INTERRUPTION_FILTER_UNKNOWN+ }++ private fun setDnd(on: Boolean): Boolean {+ val nm = notifications ?: return false+ if (!nm.isNotificationPolicyAccessGranted) return false+ nm.setInterruptionFilter(+ if (on) NotificationManager.INTERRUPTION_FILTER_PRIORITY+ else NotificationManager.INTERRUPTION_FILTER_ALL,+ )+ return true+ }++ private fun readRinger(): String = when (audio?.ringerMode) {+ AudioManager.RINGER_MODE_SILENT -> "silent"+ AudioManager.RINGER_MODE_VIBRATE -> "vibrate"+ else -> "ring"+ }++ private fun setRinger(mode: String): Boolean {+ val am = audio ?: return false+ val target = when (mode) {+ "ring" -> AudioManager.RINGER_MODE_NORMAL+ "vibrate" -> AudioManager.RINGER_MODE_VIBRATE+ "silent" -> {+ if (notifications?.isNotificationPolicyAccessGranted != true) return false+ AudioManager.RINGER_MODE_SILENT+ }+ else -> return false+ }+ // Leaving silent mode when DND was turned on by silent ringer requires policy access too.+ if (am.ringerMode == AudioManager.RINGER_MODE_SILENT &&+ notifications?.isNotificationPolicyAccessGranted == false+ ) {+ return false+ }+ am.ringerMode = target+ return true+ }++ private fun setFlashlight(on: Boolean): Boolean {+ val camId = torchCameraId ?: return false+ val cm = camera ?: return false+ cm.setTorchMode(camId, on)+ torchOn = on+ return true+ }++ private fun readVolume(): Int {+ val am = audio ?: return 0+ val min = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {+ am.getStreamMinVolume(AudioManager.STREAM_MUSIC)+ } else {+ 0+ }+ val max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(min + 1)+ val cur = am.getStreamVolume(AudioManager.STREAM_MUSIC).coerceIn(min, max)+ return (((cur - min) * 100f) / (max - min)).roundToInt().coerceIn(0, 100)+ }++ private fun setVolume(level: Int): Boolean {+ val am = audio ?: return false+ val clamped = level.coerceIn(0, 100)+ val min = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {+ am.getStreamMinVolume(AudioManager.STREAM_MUSIC)+ } else {+ 0+ }+ val max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(min + 1)+ val index = min + ((clamped / 100f) * (max - min)).roundToInt()+ am.setStreamVolume(AudioManager.STREAM_MUSIC, index.coerceIn(min, max), 0)+ return true+ }++ private fun readBrightness(): Int {+ val raw = runCatching {+ Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128)+ }.getOrDefault(128)+ return ((raw.coerceIn(0, 255) * 100f) / 255f).roundToInt().coerceIn(0, 100)+ }++ private fun setBrightness(level: Int): Boolean {+ val raw = ((level.coerceIn(0, 100) * 255f) / 100f).roundToInt().coerceIn(0, 255)+ if (Settings.System.canWrite(context)) {+ return Settings.System.putInt(+ context.contentResolver,+ Settings.System.SCREEN_BRIGHTNESS,+ raw,+ )+ }+ if (Elevated.running) {+ return Elevated.runCommand("settings put system screen_brightness $raw")+ }+ return false+ }++ private fun readWifi(): Boolean = runCatching { wifi?.isWifiEnabled == true }.getOrDefault(false)++ private fun readBluetooth(): Boolean =+ runCatching { bluetooth?.adapter?.isEnabled }.getOrNull()+ ?: runCatching {+ Settings.Global.getInt(context.contentResolver, Settings.Global.BLUETOOTH_ON, 0) != 0+ }.getOrDefault(false)++ private fun findTorchCamera(): String? = runCatching {+ if (Build.HARDWARE == "ranchu" || Build.HARDWARE == "goldfish" || Build.MODEL.contains("sdk_gphone")) {+ return null+ }+ val cm = camera ?: return null+ var fallback: String? = null+ for (id in cm.cameraIdList) {+ val chars = cm.getCameraCharacteristics(id)+ if (chars.get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true) {+ if (chars.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK) {+ return id+ }+ if (fallback == null) fallback = id+ }+ }+ fallback+ }.getOrNull()++ companion object {+ private const val TAG = "PhoneToggles"+ private const val DEBOUNCE_MS = 120L+ private const val FOLLOW_UP_MS = 450L+ private const val VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION"++ fun hasDndAccess(context: Context): Boolean =+ context.getSystemService(NotificationManager::class.java)?.isNotificationPolicyAccessGranted == true++ fun hasWriteSettings(context: Context): Boolean = Settings.System.canWrite(context)++ fun canChangeDnd(context: Context): Boolean = hasDndAccess(context)++ fun canChangeBrightness(context: Context): Boolean =+ hasWriteSettings(context) || Elevated.running++ fun dndSettingsIntent(): Intent =+ Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)++ fun writeSettingsIntent(context: Context): Intent =+ Intent(+ Settings.ACTION_MANAGE_WRITE_SETTINGS,+ Uri.fromParts("package", context.packageName, null),+ ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ }+}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.ktindex 9fba2f2..83a2c15 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@@ -56,6 +56,7 @@ import app.nectarlink.android.elevated.PairingNotificationimport app.nectarlink.android.mirror.InputServiceimport app.nectarlink.android.photos.RecentPhotosimport app.nectarlink.android.sms.PhoneSms+import app.nectarlink.android.toggles.PhoneTogglesimport app.nectarlink.android.update.AppUpdaterimport app.nectarlink.android.update.CheckForUpdatesimport app.nectarlink.android.core.CoreState@@ -131,6 +132,8 @@ fun SettingsScreen(}Section(stringResource(R.string.settings_control)) {+ DndAccess(state.dndAccess)+ WriteSettingsAccess(state.writeSettingsAccess || state.elevated)ControlAccess(state.inputAccess)ElevatedAccess()}@@ -296,6 +299,50 @@ private fun NotificationAccess(granted: Boolean) {}}+/** Do Not Disturb and silent ringer control from a PC. */+@Composable+private fun DndAccess(granted: Boolean) {+ val context = LocalContext.current+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.weight(1f).padding(end = 12.dp)) {+ Text(stringResource(R.string.dnd_access_title), style = MaterialTheme.typography.titleSmall)+ Text(+ stringResource(if (granted) R.string.dnd_access_on else R.string.dnd_access_off),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ val open = { context.startActivity(PhoneToggles.dndSettingsIntent()) }+ if (granted) {+ OutlinedButton(onClick = open) { Text(stringResource(R.string.action_manage)) }+ } else {+ Button(onClick = open) { Text(stringResource(R.string.action_allow)) }+ }+ }+}++/** Screen brightness control from a PC (Modify system settings, or Elevated). */+@Composable+private fun WriteSettingsAccess(granted: Boolean) {+ val context = LocalContext.current+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.weight(1f).padding(end = 12.dp)) {+ Text(stringResource(R.string.write_settings_title), style = MaterialTheme.typography.titleSmall)+ Text(+ stringResource(if (granted) R.string.write_settings_on else R.string.write_settings_off),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ val open = { context.startActivity(PhoneToggles.writeSettingsIntent(context)) }+ if (granted) {+ OutlinedButton(onClick = open) { Text(stringResource(R.string.action_manage)) }+ } else {+ Button(onClick = open) { Text(stringResource(R.string.action_allow)) }+ }+ }+}+/** Control from the PC: Nectarlink's accessibility service, turned on in Android's settings. */@Composableprivate fun ControlAccess(on: Boolean) {diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex c337e4e..6c7fe20 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -73,6 +73,12 @@<string name="control_title">Use your PC\'s mouse and keyboard</string><string name="control_on">On: while your screen is shown on your PC, you can tap, swipe and type from there.</string><string name="control_off">While your screen is shown on your PC, tap, swipe and type from there. Turn on Nectarlink in Accessibility.</string>+ <string name="dnd_access_title">Do Not Disturb and silent mode</string>+ <string name="dnd_access_on">On: your PC can turn Do Not Disturb on or off and set the ringer to silent.</string>+ <string name="dnd_access_off">Let your PC turn Do Not Disturb on or off and set the ringer to silent.</string>+ <string name="write_settings_title">Screen brightness</string>+ <string name="write_settings_on">On: your PC can adjust this phone\'s screen brightness.</string>+ <string name="write_settings_off">Let your PC adjust this phone\'s screen brightness.</string><string name="local_network_title">Reach your PC on this network</string><string name="local_network_text">Android asks before an app talks to devices on your network. Nectarlink needs it to reach your PC.</string><string name="channel_elevated">Wireless debugging setup</string>diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex ccd6d4c..e278cda 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -112,6 +112,12 @@ enum Command {#[arg(requires = "name")]state: Option<OnOff>,},+ /// Show a paired phone's quick settings, or change one with `toggles <device> set <id> <value>`.+ Toggles {+ device: String,+ #[command(subcommand)]+ action: Option<TogglesArg>,+ },/// Stay online and print events until Ctrl+C.Run,/// Send files to a paired device and wait until they've arrived.@@ -563,6 +569,13 @@ enum OnOff {Off,}+#[derive(Debug, Subcommand)]+enum TogglesArg {+ /// Change one of the phone's quick settings (`dnd`, `ringer`, `flashlight`,+ /// `volume`, `brightness`, `wifi`, `bluetooth`).+ Set { id: String, value: String },+}+/// Where `mirror` saves the video, and what arrived.static RECORDING: std::sync::OnceLock<std::sync::Arc<Recording>> = std::sync::OnceLock::new();@@ -904,6 +917,24 @@ static CALL_NODE: std::sync::OnceLock<Node> = std::sync::OnceLock::new();/// Whether `incoming-call` offers in-call controls (without --basic).static CALL_CONTROLS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+/// Sample quick settings for a test phone (`demo` or `--as-phone`).+static TOGGLES: std::sync::Mutex<Option<nectarlink_core::PhoneToggles>> = std::sync::Mutex::new(None);+static TOGGLES_NODE: std::sync::OnceLock<Node> = std::sync::OnceLock::new();++fn sample_toggles() -> nectarlink_core::PhoneToggles {+ let mut lock = TOGGLES.lock().unwrap();+ lock.get_or_insert_with(|| nectarlink_core::PhoneToggles {+ dnd: false,+ ringer: "ring".into(),+ flashlight: Some(false),+ volume: 60,+ brightness: 70,+ wifi: true,+ bluetooth: true,+ })+ .clone()+}+/// The picture `photo` announced, for PCs that ask for it.static PHOTO: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();const PHOTO_ID: &str = "cli-photo";@@ -1651,6 +1682,52 @@ impl Platform for TerminalPlatform {println!("Remote input: {input:?}");Ok(())}+ fn set_phone_toggle(+ &self,+ id: &str,+ value: &nectarlink_core::PhoneToggleValue,+ ) -> std::result::Result<(), String> {+ use nectarlink_core::PhoneToggleValue as V;+ let mut t = sample_toggles();+ match (id, value) {+ ("dnd", V::Bool(on)) => {+ t.dnd = *on;+ println!("Phone DND is now {}.", if *on { "on" } else { "off" });+ }+ ("ringer", V::Mode(mode)) => {+ t.ringer = mode.clone();+ println!("Phone ringer is now {mode}.");+ }+ ("flashlight", V::Bool(on)) => {+ t.flashlight = Some(*on);+ println!("Phone flashlight is now {}.", if *on { "on" } else { "off" });+ }+ ("volume", V::Level(level)) => {+ t.volume = *level;+ println!("Phone volume is now {level}%.");+ }+ ("brightness", V::Level(level)) => {+ t.brightness = *level;+ println!("Phone brightness is now {level}%.");+ }+ ("wifi", V::Bool(on)) => {+ t.wifi = *on;+ println!("Phone Wi-Fi is now {}.", if *on { "on" } else { "off" });+ }+ ("bluetooth", V::Bool(on)) => {+ t.bluetooth = *on;+ println!("Phone Bluetooth is now {}.", if *on { "on" } else { "off" });+ }+ _ => return Err("invalid toggle".into()),+ }+ *TOGGLES.lock().unwrap() = Some(t.clone());+ if let Some(node) = TOGGLES_NODE.get().cloned() {+ tokio::runtime::Handle::current().spawn(async move {+ let _ = node.toggles_changed(t).await;+ });+ }+ Ok(())+ }}fn main() -> Result<()> {@@ -1700,9 +1777,14 @@ async fn start_node(cli: &Cli) -> Result<Node> {config.power = power;if !cli.as_phone {config.capabilities.push(nectarlink_core::RECORDER.into());+ config.capabilities.push(nectarlink_core::TOGGLES_SHOW.into());}let extra_caps = config.capabilities.clone();let node = Node::start(config, Arc::new(TerminalPlatform)).await.context("failed to start")?;+ if cli.as_phone {+ let _ = TOGGLES_NODE.set(node.clone());+ let _ = node.toggles_changed(sample_toggles()).await;+ }if !cli.offers.is_empty() {let mut offers = extra_caps;for o in &cli.offers {@@ -1862,6 +1944,38 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {node.set_device_toggle(id, name, on)?;println!("{name} is now {}", if on { "on" } else { "off" });}+ Command::Toggles { device, action: None } => {+ let mut events = node.events();+ let id = resolve(node, device)?;+ wait_until_online(node, id).await?;+ let toggles = match node.phone_toggles(id) {+ Some(t) => t,+ None => {+ let wait = async {+ loop {+ if let Ok(NodeEvent::PhoneToggles { device: d, toggles }) = events.recv().await+ && d == id+ {+ return toggles;+ }+ }+ };+ tokio::time::timeout(Duration::from_secs(5), wait)+ .await+ .context("the phone didn't report its quick settings")?+ }+ };+ print_phone_toggles(node, id, &toggles)?;+ }+ Command::Toggles { device, action: Some(TogglesArg::Set { id: toggle_id, value }) } => {+ let parsed = parse_phone_toggle_value(toggle_id, value)?;+ let id = resolve(node, device)?;+ wait_until_online(node, id).await?;+ node.set_phone_toggle(id, toggle_id.clone(), parsed)+ .await+ .with_context(|| format!("couldn't set {toggle_id}"))?;+ println!("{toggle_id} set to {value}.");+ }Command::Run => watch(node, false).await?,Command::Photos { device: None, .. } => {let mut offers = cli.offers.clone();@@ -2318,6 +2432,7 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {sample_photos();let _ = TEXTS_NODE.set(node.clone());let _ = CALL_NODE.set(node.clone());+ let _ = TOGGLES_NODE.set(node.clone());CALL_CONTROLS.store(true, std::sync::atomic::Ordering::Relaxed);let mut offers = cli.offers.clone();offers.extend(@@ -2336,10 +2451,22 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {nectarlink_core::CALLS_DIAL,nectarlink_core::CONTACTS_READ,nectarlink_core::PHOTOS_READ,+ nectarlink_core::TOGGLES_READ,+ nectarlink_core::TOGGLES_RINGER,+ nectarlink_core::TOGGLES_VOLUME,+ nectarlink_core::TOGGLES_FLASHLIGHT,+ nectarlink_core::TOGGLES_DND,+ nectarlink_core::TOGGLES_BRIGHTNESS,].map(str::to_owned),);+ if node_power(cli) == PowerLevel::Elevated {+ offers.extend(+ [nectarlink_core::TOGGLES_WIFI, nectarlink_core::TOGGLES_BLUETOOTH].map(str::to_owned),+ );+ }node.update_power(node_power(cli), offers).await;+ let _ = node.toggles_changed(sample_toggles()).await;let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;let samples = [("Messages", "Sam Rivera", "Are we still on for dinner tonight?", true),@@ -3209,6 +3336,9 @@ fn print_event(node: &Node, event: &NodeEvent) {NodeEvent::CallLogChanged { device } => println!("{}: call log changed", name(device)),NodeEvent::ContactsChanged { device } => println!("{}: contacts changed", name(device)),NodeEvent::PhotosChanged { device } => println!("{}: photo library changed", name(device)),+ NodeEvent::PhoneToggles { device, toggles } => {+ println!("{}: toggles {}", name(device), summarize_toggles(toggles));+ }NodeEvent::RemoteInputRequested { device } => println!("{}: asked to control mouse and keyboard (allow with: nectarlink toggle {} remote_input on)",name(device),@@ -3297,6 +3427,81 @@ fn print_event(node: &Node, event: &NodeEvent) {}}+fn summarize_toggles(t: &nectarlink_core::PhoneToggles) -> String {+ let yn = |b: bool| if b { "on" } else { "off" };+ let yn_opt = |b: Option<bool>| match b {+ Some(true) => "on",+ Some(false) => "off",+ None => "—",+ };+ format!(+ "dnd={} ringer={} flash={} vol={}% bright={}% wifi={} bt={}",+ yn(t.dnd),+ t.ringer,+ yn_opt(t.flashlight),+ t.volume,+ t.brightness,+ yn(t.wifi),+ yn(t.bluetooth),+ )+}++fn parse_phone_toggle_value(id: &str, raw: &str) -> Result<nectarlink_core::PhoneToggleValue> {+ use nectarlink_core::PhoneToggleValue as V;+ let s = raw.trim().to_ascii_lowercase();+ match id {+ "dnd" | "flashlight" | "wifi" | "bluetooth" => match s.as_str() {+ "on" | "true" | "1" => Ok(V::Bool(true)),+ "off" | "false" | "0" => Ok(V::Bool(false)),+ _ => bail!("{id} takes `on` or `off`"),+ },+ "ringer" => match s.as_str() {+ "ring" | "vibrate" | "silent" => Ok(V::Mode(s)),+ _ => bail!("ringer takes `ring`, `vibrate`, or `silent`"),+ },+ "volume" | "brightness" => {+ let level: u8 = s+ .trim_end_matches('%')+ .parse()+ .ok()+ .filter(|&v| v <= 100)+ .with_context(|| format!("{id} takes 0..=100"))?;+ Ok(V::Level(level))+ }+ _ => bail!(+ "unknown toggle {id:?}; expected dnd, ringer, flashlight, volume, brightness, wifi or bluetooth"+ ),+ }+}++fn print_phone_toggles(node: &Node, id: DeviceId, t: &nectarlink_core::PhoneToggles) -> Result<()> {+ let matrix = node.capabilities(id)?;+ let yn = |b: bool| if b { "on" } else { "off" }.to_owned();+ let yn_opt = |b: Option<bool>| match b {+ Some(true) => "on".to_owned(),+ Some(false) => "off".to_owned(),+ None => "—".to_owned(),+ };+ let rows = [+ ("dnd", yn(t.dnd), "toggles.dnd"),+ ("ringer", t.ringer.clone(), "toggles.ringer"),+ ("flashlight", yn_opt(t.flashlight), "toggles.flashlight"),+ ("volume", format!("{}%", t.volume), "toggles.volume"),+ ("brightness", format!("{}%", t.brightness), "toggles.brightness"),+ ("wifi", yn(t.wifi), "toggles.wifi"),+ ("bluetooth", yn(t.bluetooth), "toggles.bluetooth"),+ ];+ for (name, val, feat) in rows {+ let note = match matrix.state(feat) {+ Some(FeatureState::Available) => String::new(),+ Some(state) => format!(" ({})", describe_state(&state)),+ None => String::new(),+ };+ println!("{name:<12} {val:<10}{note}");+ }+ Ok(())+}+fn print_capabilities(node: &Node, id: DeviceId) -> Result<()> {let matrix = node.capabilities(id)?;let mut group = None;diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rsindex e68819a..ec6da1e 100644--- a/core/nectarlink-core/src/config.rs+++ b/core/nectarlink-core/src/config.rs@@ -278,6 +278,13 @@ pub trait Platform: Send + Sync + 'static {) -> Result<(), String> {Err("this device doesn't take remote input".into())}++ /// Change one of this phone's quick settings (`phone.toggle.set`,+ /// `docs/protocol/toggles.md`). `id` and `value` have been validated and+ /// checked against this phone's capabilities. `Err` holds a reason for logs.+ fn set_phone_toggle(&self, _id: &str, _value: &crate::PhoneToggleValue) -> Result<(), String> {+ Err("this device has no phone toggles".into())+ }}/// A platform that does nothing; useful for tests and headless tools.diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rsindex 2074a64..9bb99c8 100644--- a/core/nectarlink-core/src/events.rs+++ b/core/nectarlink-core/src/events.rs@@ -169,4 +169,9 @@ pub enum NodeEvent {RemoteInputRequested {device: DeviceId,},+ /// A paired phone's quick settings state (on connect and on change).+ PhoneToggles {+ device: DeviceId,+ toggles: crate::PhoneToggles,+ },}diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rsindex 26e0618..d91c2bf 100644--- a/core/nectarlink-core/src/features.rs+++ b/core/nectarlink-core/src/features.rs@@ -28,6 +28,8 @@ pub enum Role {#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub enum Permission {NotificationAccess,+ DoNotDisturb,+ WriteSettings,Sms,Phone,Contacts,@@ -40,6 +42,8 @@ impl Permission {pub const fn as_str(self) -> &'static str {match self {Permission::NotificationAccess => "notification_access",+ Permission::DoNotDisturb => "dnd_access",+ Permission::WriteSettings => "write_settings",Permission::Sms => "sms",Permission::Phone => "phone",Permission::Contacts => "contacts",@@ -334,6 +338,7 @@ pub const DEVICE_TOGGLES: &[(&str, bool)] = &[("media", true),("photos", true),("recordings", true),+ ("toggles", true),("pc_actions", true),("mirroring", true),// Controlling this PC's mouse and keyboard is opt-in.@@ -563,6 +568,84 @@ pub const FEATURES: &[FeatureDef] = &[requires: &[phone("link.open", UPDATE)],partial: None,},+ FeatureDef {+ id: "toggles.dnd",+ group: FeatureGroup::Device,+ requires: &[+ phone("toggles.dnd", Unlock::Permission(Permission::DoNotDisturb)),+ desktop("toggles.show", UPDATE),+ DeviceToggle("toggles"),+ ],+ partial: None,+ },+ FeatureDef {+ id: "toggles.ringer",+ group: FeatureGroup::Device,+ requires: &[+ phone("toggles.ringer", UPDATE),+ phone("toggles.dnd", Unlock::Permission(Permission::DoNotDisturb)),+ desktop("toggles.show", UPDATE),+ DeviceToggle("toggles"),+ ],+ partial: Some(PartialDef {+ requires: &[+ phone("toggles.ringer", UPDATE),+ desktop("toggles.show", UPDATE),+ DeviceToggle("toggles"),+ ],+ limit: "toggles.limit.silent",+ }),+ },+ FeatureDef {+ id: "toggles.flashlight",+ group: FeatureGroup::Device,+ requires: &[+ phone("toggles.flashlight", Unlock::Power(PowerLevel::Basic)),+ desktop("toggles.show", UPDATE),+ DeviceToggle("toggles"),+ ],+ partial: None,+ },+ FeatureDef {+ id: "toggles.volume",+ group: FeatureGroup::Device,+ requires: &[+ phone("toggles.volume", UPDATE),+ desktop("toggles.show", UPDATE),+ DeviceToggle("toggles"),+ ],+ partial: None,+ },+ FeatureDef {+ id: "toggles.brightness",+ group: FeatureGroup::Device,+ requires: &[+ phone("toggles.brightness", Unlock::Permission(Permission::WriteSettings)),+ desktop("toggles.show", UPDATE),+ DeviceToggle("toggles"),+ ],+ partial: None,+ },+ FeatureDef {+ id: "toggles.wifi",+ group: FeatureGroup::Device,+ requires: &[+ phone("toggles.wifi", ELEVATED),+ desktop("toggles.show", UPDATE),+ DeviceToggle("toggles"),+ ],+ partial: None,+ },+ FeatureDef {+ id: "toggles.bluetooth",+ group: FeatureGroup::Device,+ requires: &[+ phone("toggles.bluetooth", ELEVATED),+ desktop("toggles.show", UPDATE),+ DeviceToggle("toggles"),+ ],+ partial: None,+ },// NotificationsFeatureDef {id: "notifications.mirror",@@ -815,12 +898,19 @@ mod tests {"media.control","media.remote","camera.stream",+ "toggles.read",+ "toggles.ringer",+ "toggles.volume",+ "toggles.flashlight",+ "toggles.dnd",+ "toggles.brightness",];const PC: &[&str] = &["pc.power","files.transfer","files.browse","recorder",+ "toggles.show","media.control","media.remote","input.inject",@@ -893,6 +983,8 @@ mod tests {"mirror.input","mirror.virtual_display","mirror.audio",+ "toggles.wifi",+ "toggles.bluetooth",]);let m = matrix(&facts(DeviceKind::Phone, "android", "16", PowerLevel::Elevated, &caps));for id in [@@ -901,11 +993,68 @@ mod tests {"mirroring.control","mirroring.app_windows","mirroring.audio",+ "toggles.wifi",+ "toggles.bluetooth",] {assert_eq!(m.state(id), Some(FeatureState::Available), "{id}");}}+ #[test]+ fn phone_toggles_reflect_permissions_hardware_and_power() {+ // Basic phone without DND access, WriteSettings, or flash hardware (e.g. emulator).+ let minimal = facts(+ DeviceKind::Phone,+ "android",+ "16",+ PowerLevel::Basic,+ &["toggles.read", "toggles.ringer", "toggles.volume"],+ );+ let m = matrix(&minimal);+ assert_eq!(m.state("toggles.volume"), Some(FeatureState::Available));+ assert_eq!(+ m.state("toggles.ringer"),+ Some(FeatureState::Partial {+ limit: "toggles.limit.silent",+ upgrade: Some(Upgrade {+ action: UpgradeAction::GrantPermission(Permission::DoNotDisturb),+ effort: Effort::Instant,+ }),+ })+ );+ assert_eq!(+ m.state("toggles.dnd"),+ Some(locked(UpgradeAction::GrantPermission(Permission::DoNotDisturb), Effort::Instant))+ );+ assert_eq!(+ m.state("toggles.brightness"),+ Some(locked(UpgradeAction::GrantPermission(Permission::WriteSettings), Effort::Instant))+ );+ assert_eq!(+ m.state("toggles.flashlight"),+ Some(FeatureState::Unsupported { reason: UnsupportedReason::NotOnThisDevice })+ );+ for id in ["toggles.wifi", "toggles.bluetooth"] {+ assert_eq!(+ m.state(id),+ Some(locked(UpgradeAction::RaisePower(PowerLevel::Elevated), Effort::Minutes(2))),+ "{id}"+ );+ }++ // Turning off the `toggles` device toggle locks them behind the toggle.+ let toggles = HashMap::from([("toggles".to_owned(), false)]);+ let m_off = matrix_with(+ &facts(DeviceKind::Phone, "android", "16", PowerLevel::Basic, BASIC_PHONE),+ &pc(),+ &toggles,+ );+ assert_eq!(+ m_off.state("toggles.volume"),+ Some(locked(UpgradeAction::EnableDeviceToggle("toggles"), Effort::Instant))+ );+ }+#[test]fn missing_capability_at_the_right_power_is_unsupported() {// Elevated, but this phone can't do auto clipboard: manual still works.diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsindex d61d1a1..4dd6168 100644--- a/core/nectarlink-core/src/lib.rs+++ b/core/nectarlink-core/src/lib.rs@@ -25,6 +25,7 @@ pub mod remote;mod session;mod sms;mod store;+pub mod toggles;mod transfer;pub use actions::PowerAction;@@ -46,8 +47,9 @@ pub use nectarlink_protocol::{messages::{Battery, CLIP_MAX_BYTES, CallControls, CallLogEntry, CallState, Contact, ContactNumber, DeviceInfo,DeviceKind, MediaPlayer, MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorResize, MirrorStart,- Notification, NotificationAction, PhoneApp, PhotoAlbum, PhotoItem, PhotoNew as Photo, PhotoThumb,- PowerLevel, SmsMessage, SmsPart, SmsThread, TouchAction,+ Notification, NotificationAction, PhoneApp, PhoneToggleSet, PhoneToggleValue, PhoneToggles,+ PhotoAlbum, PhotoItem, PhotoNew as Photo, PhotoThumb, PowerLevel, SmsMessage, SmsPart, SmsThread,+ TouchAction,calls::{CONTROL as CALLS_CONTROL, DIAL as CALLS_DIAL, IN_CALL as CALLS_IN_CALL, LOG as CALLS_LOG,SHOW as CALLS_SHOW, STATE as CALLS_STATE,@@ -66,7 +68,14 @@ pub use nectarlink_protocol::{MAX_THUMB_BATCH as PHOTO_MAX_THUMB_BATCH, MAX_THUMB_BYTES as PHOTO_MAX_THUMB_BYTES,READ as PHOTOS_READ, SHOW as PHOTOS_SHOW,},+ ringer_modes,sms::{READ as SMS_READ, SEND as SMS_SEND, SHOW as SMS_SHOW},+ toggle_ids,+ toggles::{+ BLUETOOTH as TOGGLES_BLUETOOTH, BRIGHTNESS as TOGGLES_BRIGHTNESS, DND as TOGGLES_DND,+ FLASHLIGHT as TOGGLES_FLASHLIGHT, READ as TOGGLES_READ, RINGER as TOGGLES_RINGER,+ SHOW as TOGGLES_SHOW, VOLUME as TOGGLES_VOLUME, WIFI as TOGGLES_WIFI,+ },},pairing::PairingUri,};diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rsindex 03a4918..11aec24 100644--- a/core/nectarlink-core/src/node.rs+++ b/core/nectarlink-core/src/node.rs@@ -120,6 +120,8 @@ pub(crate) struct Shared {pub players: crate::media::Players,/// This phone's call in progress (docs/protocol/calls.md).pub(crate) calls: crate::calls::Current,+ /// This phone's quick settings state (docs/protocol/toggles.md).+ pub(crate) toggles: crate::toggles::Current,/// Stop signals for phone screens shown here, by phone.pub(crate) mirror_stops: Mutex<HashMap<MirrorStop, Arc<tokio::sync::Notify>>>,/// Per-peer rate limiters and prompt state for remote input.@@ -297,6 +299,7 @@ impl Shared {lock(&self.links).remove(peer);lock(&self.matrices).remove(peer);lock(&self.remote).remove_peer(peer);+ self.toggles.remove_peer(peer);if existed {self.emit(NodeEvent::DeviceRemoved(*peer));}@@ -365,6 +368,7 @@ impl Shared {shared.send_notification_snapshot(&s).await;shared.send_media_state(&s).await;shared.send_call_state(&s).await;+ shared.send_toggles_state(&s).await;});Some(session)}@@ -375,6 +379,7 @@ impl Shared {let current = sessions.get(&ended.peer).is_some_and(|current| Arc::ptr_eq(current, ended));if current {sessions.remove(&ended.peer);+ self.toggles.remove_peer(&ended.peer);if paired {tracing::info!(peer = %ended.peer.short(), "disconnected");// Still under the lock: a new session for the peer can't@@ -621,6 +626,7 @@ impl Node {notifications: Feed::default(),players: Default::default(),calls: Default::default(),+ toggles: Default::default(),mirror_stops: Mutex::new(HashMap::new()),remote: Mutex::new(Default::default()),data_dir: config.data_dir.clone(),@@ -743,6 +749,7 @@ impl Node {let _ = session.send(Envelope::empty(types::MEDIA_SYNC)).await;self.shared.send_notification_snapshot(&session).await;self.shared.send_media_state(&session).await;+ self.shared.send_toggles_state(&session).await;}}@@ -848,6 +855,9 @@ impl Node {if toggle == crate::media::TOGGLE {self.shared.media_toggled(peer, enabled);}+ if toggle == crate::toggles::TOGGLE {+ self.shared.toggles_toggled(peer, enabled);+ }Ok(())}@@ -1262,6 +1272,32 @@ impl Node {Ok(())}+ // ---- Phone toggles (docs/protocol/toggles.md) ----++ /// The latest quick settings reported by a connected phone, if any.+ pub fn phone_toggles(&self, peer: DeviceId) -> Option<crate::PhoneToggles> {+ self.shared.toggles.peer(&peer)+ }++ /// This phone's quick settings state (on startup and whenever any toggle+ /// changes); sent to every connected PC the user allows (and to PCs that+ /// connect later).+ pub async fn toggles_changed(&self, toggles: crate::PhoneToggles) -> Result<()> {+ self.shared.toggles_changed(toggles).await+ }++ /// Asks a paired phone to change one quick setting (`id`: `dnd`, `ringer`,+ /// `flashlight`, `volume`, `brightness`, `wifi`, `bluetooth`).+ pub async fn set_phone_toggle(+ &self,+ peer: DeviceId,+ id: String,+ value: crate::PhoneToggleValue,+ ) -> Result<()> {+ let session = self.connected(&peer)?;+ crate::toggles::set(&self.shared, &session, id, value).await+ }+// ---- Local state reported by the app ----/// Reports this device's battery; forwarded to connected devices.diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rsindex 129d929..8c5f730 100644--- a/core/nectarlink-core/src/session.rs+++ b/core/nectarlink-core/src/session.rs@@ -363,6 +363,7 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->}let caps = update.caps.map(crate::features::sanitize_capabilities);let power = update.power.map(PowerLevel::effective);+ let had_caps = caps.is_some();if caps.is_some() || power.is_some() {shared.store.update_capabilities(&peer, caps.as_ref(), power)?;}@@ -370,6 +371,9 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->shared.emit(NodeEvent::PeerPowerChanged { device: peer, power });}shared.refresh_capabilities(&peer);+ if had_caps {+ shared.send_toggles_state(session).await;+ }}types::DEVICE_RING => {let ring: Ring = env.body()?;@@ -401,6 +405,7 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->t if t.starts_with("sms.") && crate::sms::handle(shared, session, &env).await? => {}t if t.starts_with("mirror.") && crate::mirror::handle(shared, session, &env).await? => {}t if t.starts_with("remote.") && crate::remote::handle(shared, session, &env).await? => {}+ t if t.starts_with("phone.toggle") && crate::toggles::handle(shared, session, &env).await? => {}other => {if env.id.is_some() {let reply = Envelope::error(ErrorCode::Unsupported, format!("unknown message type {other}"));diff --git a/core/nectarlink-core/src/toggles.rs b/core/nectarlink-core/src/toggles.rsnew file mode 100644index 0000000..9188c76--- /dev/null+++ b/core/nectarlink-core/src/toggles.rs@@ -0,0 +1,211 @@+// SPDX-License-Identifier: MPL-2.0+//! Phone quick settings on a PC (`docs/protocol/toggles.md`).+//!+//! A phone that offers `toggles.read` sends its current quick settings+//! (`phone.toggles`) when a session starts and after every change. A PC that+//! offers `toggles.show` displays them and sends `phone.toggle.set` for the+//! toggles the phone's Power Level and permissions allow.++use std::{+ collections::HashMap,+ sync::{Arc, Mutex},+};++pub use nectarlink_protocol::messages::{+ PhoneToggleSet, PhoneToggleValue, PhoneToggles, ringer_modes, toggle_ids,+ toggles::{+ BLUETOOTH as TOGGLES_BLUETOOTH, BRIGHTNESS as TOGGLES_BRIGHTNESS, DND as TOGGLES_DND,+ FLASHLIGHT as TOGGLES_FLASHLIGHT, READ as TOGGLES_READ, RINGER as TOGGLES_RINGER,+ SHOW as TOGGLES_SHOW, VOLUME as TOGGLES_VOLUME, WIFI as TOGGLES_WIFI,+ },+};+use nectarlink_protocol::{DeviceId, Envelope, ErrorCode, messages::types};++use crate::{+ Error, Result,+ events::NodeEvent,+ node::Shared,+ session::{REQUEST_TIMEOUT, Session},+};++/// The device toggle that allows viewing and changing phone toggles.+pub(crate) const TOGGLE: &str = "toggles";++/// This phone's latest quick settings state (sent to newly connected PCs)+/// and the latest state received from each connected phone.+#[derive(Default)]+pub(crate) struct Current {+ local: Mutex<Option<PhoneToggles>>,+ peers: Mutex<HashMap<DeviceId, PhoneToggles>>,+}++impl Current {+ pub fn get(&self) -> Option<PhoneToggles> {+ self.local.lock().unwrap_or_else(|e| e.into_inner()).clone()+ }++ fn set(&self, state: PhoneToggles) {+ *self.local.lock().unwrap_or_else(|e| e.into_inner()) = Some(state);+ }++ pub fn peer(&self, peer: &DeviceId) -> Option<PhoneToggles> {+ self.peers.lock().unwrap_or_else(|e| e.into_inner()).get(peer).cloned()+ }++ fn set_peer(&self, peer: DeviceId, state: PhoneToggles) {+ self.peers.lock().unwrap_or_else(|e| e.into_inner()).insert(peer, state);+ }++ pub fn remove_peer(&self, peer: &DeviceId) {+ self.peers.lock().unwrap_or_else(|e| e.into_inner()).remove(peer);+ }+}++/// The phone capability required to change toggle `id`.+pub fn required_capability(id: &str) -> Option<&'static str> {+ Some(match id {+ toggle_ids::DND => TOGGLES_DND,+ toggle_ids::RINGER => TOGGLES_RINGER,+ toggle_ids::FLASHLIGHT => TOGGLES_FLASHLIGHT,+ toggle_ids::VOLUME => TOGGLES_VOLUME,+ toggle_ids::BRIGHTNESS => TOGGLES_BRIGHTNESS,+ toggle_ids::WIFI => TOGGLES_WIFI,+ toggle_ids::BLUETOOTH => TOGGLES_BLUETOOTH,+ _ => return None,+ })+}++impl Shared {+ fn shows_toggles(&self, peer: &DeviceId) -> bool {+ self.store.get_peer(peer).ok().flatten().is_some_and(|p| p.caps.contains(TOGGLES_SHOW))+ }++ /// Sends this phone's current toggles to `session` if it shows them and+ /// the `toggles` device toggle is on.+ pub(crate) async fn send_toggles_state(&self, session: &Arc<Session>) {+ if !self.shows_toggles(&session.peer) || !self.toggle_on(&session.peer, TOGGLE) {+ return;+ }+ let Some(state) = self.toggles.get() else { return };+ if let Ok(env) = Envelope::new(types::PHONE_TOGGLES, &state) {+ let _ = session.send(env).await;+ }+ }++ /// Updates this phone's toggles state and sends it to connected PCs.+ pub(crate) async fn toggles_changed(&self, state: PhoneToggles) -> Result<()> {+ let state = state.sanitized().ok_or_else(|| Error::Protocol("invalid phone toggles".into()))?;+ self.toggles.set(state.clone());+ let env = Envelope::new(types::PHONE_TOGGLES, &state)?;+ for session in self.live_sessions() {+ if self.shows_toggles(&session.peer) && self.toggle_on(&session.peer, TOGGLE) {+ let _ = session.send(env.clone()).await;+ }+ }+ Ok(())+ }++ /// Brings a connected peer up to date when the `toggles` device toggle is+ /// flipped on this device.+ pub(crate) fn toggles_toggled(self: &Arc<Self>, peer: DeviceId, enabled: bool) {+ if !enabled {+ self.toggles.remove_peer(&peer);+ return;+ }+ if self.toggles.get().is_none() {+ return;+ }+ if let Some(session) = self.session(&peer) {+ let shared = self.clone();+ self.runtime.spawn(async move {+ shared.send_toggles_state(&session).await;+ });+ }+ }+}++/// Asks a paired phone to change one toggle (`phone.toggle.set`).+pub(crate) async fn set(+ shared: &Arc<Shared>,+ session: &Arc<Session>,+ id: String,+ value: PhoneToggleValue,+) -> Result<()> {+ let req = PhoneToggleSet { id, value };+ if !req.is_valid() {+ return Err(Error::Protocol("invalid phone toggle or value".into()));+ }+ if !shared.toggle_on(&session.peer, TOGGLE) {+ return Err(Error::Denied);+ }+ let Some(cap) = required_capability(&req.id) else {+ return Err(Error::Protocol("unknown toggle".into()));+ };+ let peer_caps = shared.store.get_peer(&session.peer)?.map(|p| p.caps).unwrap_or_default();+ let silent_needs_dnd = req.id == toggle_ids::RINGER+ && matches!(&req.value, PhoneToggleValue::Mode(m) if m == ringer_modes::SILENT);+ if !peer_caps.contains(cap) || (silent_needs_dnd && !peer_caps.contains(TOGGLES_DND)) {+ return Err(Error::Unsupported);+ }+ let env = Envelope::new(types::PHONE_TOGGLE_SET, &req)?;+ session.request(env, REQUEST_TIMEOUT).await?.expect(types::OK)?;+ Ok(())+}++/// Handles `phone.toggles` and `phone.toggle.set`.+pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {+ let peer = session.peer;+ match env.t.as_str() {+ types::PHONE_TOGGLES => {+ if shared.toggle_on(&peer, TOGGLE) {+ let state: PhoneToggles = env.body()?;+ if let Some(toggles) = state.sanitized() {+ shared.toggles.set_peer(peer, toggles.clone());+ shared.emit(NodeEvent::PhoneToggles { device: peer, toggles });+ }+ }+ }+ types::PHONE_TOGGLE_SET => {+ let req: PhoneToggleSet = env.body()?;+ let reply = run_set(shared, &peer, req).await;+ session.send(reply.reply_to(env.id)).await?;+ }+ _ => return Ok(false),+ }+ Ok(true)+}++async fn run_set(shared: &Arc<Shared>, peer: &DeviceId, req: PhoneToggleSet) -> Envelope {+ if !req.is_valid() {+ return Envelope::error(ErrorCode::BadMessage, "invalid toggle or value");+ }+ if !shared.toggle_on(peer, TOGGLE) {+ return Envelope::error(ErrorCode::Denied, "toggles are off for this device");+ }+ let Some(cap) = required_capability(&req.id) else {+ return Envelope::error(ErrorCode::BadMessage, "unknown toggle");+ };+ let caps = shared.local_capabilities();+ let silent_needs_dnd = req.id == toggle_ids::RINGER+ && matches!(&req.value, PhoneToggleValue::Mode(m) if m == ringer_modes::SILENT);+ let no_flash =+ req.id == toggle_ids::FLASHLIGHT && shared.toggles.get().is_some_and(|t| t.flashlight.is_none());+ if !caps.iter().any(|c| c == cap)+ || (silent_needs_dnd && !caps.iter().any(|c| c == TOGGLES_DND))+ || no_flash+ {+ return Envelope::error(ErrorCode::Unsupported, "this toggle is not available");+ }+ let platform = shared.platform.clone();+ let PhoneToggleSet { id, value } = req;+ let ran = tokio::task::spawn_blocking(move || platform.set_phone_toggle(&id, &value))+ .await+ .unwrap_or_else(|e| Err(e.to_string()));+ match ran {+ Ok(()) => Envelope::empty(types::OK),+ Err(reason) => {+ tracing::warn!(reason, "phone toggle failed");+ Envelope::error(ErrorCode::Internal, "failed")+ }+ }+}diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex a4390fb..c3d37d6 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -41,6 +41,7 @@ struct RecordingPlatform {/// Optional barrier `open_photo` waits on to simulate a slow platform call.photo_barrier: Mutex<Option<Arc<std::sync::Barrier>>>,remote_inputs: Mutex<Vec<nectarlink_core::RemoteInput>>,+ phone_toggles: Mutex<Vec<(String, nectarlink_core::PhoneToggleValue)>>,}impl Platform for RecordingPlatform {@@ -390,6 +391,10 @@ impl Platform for RecordingPlatform {self.remote_inputs.lock().unwrap().push(input);Ok(())}+ fn set_phone_toggle(&self, id: &str, value: &nectarlink_core::PhoneToggleValue) -> Result<(), String> {+ self.phone_toggles.lock().unwrap().push((id.to_owned(), value.clone()));+ Ok(())+ }}#[derive(Debug, Default)]@@ -2256,3 +2261,199 @@ async fn voice_recordings_arrive_with_markers_and_respect_capability_and_toggle(.await;assert_eq!(denied, TransferFailure::Denied);}++#[tokio::test(flavor = "multi_thread")]+async fn phone_toggles_arrive_on_connect_change_and_respect_capabilities_and_toggle() {+ use nectarlink_core::{+ PhoneToggleValue, PhoneToggles, TOGGLES_BLUETOOTH, TOGGLES_BRIGHTNESS, TOGGLES_DND,+ TOGGLES_FLASHLIGHT, TOGGLES_READ, TOGGLES_RINGER, TOGGLES_SHOW, TOGGLES_VOLUME, TOGGLES_WIFI,+ ringer_modes, toggle_ids,+ };++ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[TOGGLES_SHOW]).await;+ let mut phone = device_with(+ "Pixel",+ DeviceKind::Phone,+ &[TOGGLES_READ, TOGGLES_RINGER, TOGGLES_VOLUME, TOGGLES_FLASHLIGHT],+ )+ .await;++ let initial = PhoneToggles {+ dnd: false,+ ringer: ringer_modes::RING.into(),+ flashlight: Some(false),+ volume: 65,+ brightness: 40,+ wifi: true,+ bluetooth: true,+ };+ phone.node.toggles_changed(initial.clone()).await.unwrap();++ pair_qr(&mut pc, &mut phone).await;+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());++ // Initial state arrives on connect.+ let got = wait_for(&mut pc, "initial toggles", |e| match e {+ NodeEvent::PhoneToggles { device, toggles } if *device == phone_id => Some(toggles.clone()),+ _ => None,+ })+ .await;+ assert_eq!(got, initial);++ // Volume, ringer (vibrate), and flashlight work at Basic without extra permissions.+ with_timeout(+ "set volume",+ pc.node.set_phone_toggle(phone_id, toggle_ids::VOLUME.into(), PhoneToggleValue::Level(80)),+ )+ .await+ .unwrap();+ with_timeout(+ "set ringer vibrate",+ pc.node.set_phone_toggle(+ phone_id,+ toggle_ids::RINGER.into(),+ PhoneToggleValue::Mode(ringer_modes::VIBRATE.into()),+ ),+ )+ .await+ .unwrap();+ with_timeout(+ "set flashlight on",+ pc.node.set_phone_toggle(phone_id, toggle_ids::FLASHLIGHT.into(), PhoneToggleValue::Bool(true)),+ )+ .await+ .unwrap();++ // Silent ringer and DND require `toggles.dnd`; brightness requires `toggles.brightness`;+ // Wi-Fi requires `toggles.wifi` (Elevated).+ assert!(matches!(+ pc.node+ .set_phone_toggle(+ phone_id,+ toggle_ids::RINGER.into(),+ PhoneToggleValue::Mode(ringer_modes::SILENT.into()),+ )+ .await,+ Err(Error::Unsupported)+ ));+ assert!(matches!(+ pc.node.set_phone_toggle(phone_id, toggle_ids::DND.into(), PhoneToggleValue::Bool(true)).await,+ Err(Error::Unsupported)+ ));+ assert!(matches!(+ pc.node.set_phone_toggle(phone_id, toggle_ids::BRIGHTNESS.into(), PhoneToggleValue::Level(50)).await,+ Err(Error::Unsupported)+ ));+ assert!(matches!(+ pc.node.set_phone_toggle(phone_id, toggle_ids::WIFI.into(), PhoneToggleValue::Bool(false)).await,+ Err(Error::Unsupported)+ ));++ // Invalid IDs or out-of-range values are rejected as protocol errors.+ assert!(matches!(+ pc.node.set_phone_toggle(phone_id, "unknown".into(), PhoneToggleValue::Bool(true)).await,+ Err(Error::Protocol(_))+ ));+ assert!(matches!(+ pc.node.set_phone_toggle(phone_id, toggle_ids::VOLUME.into(), PhoneToggleValue::Level(101)).await,+ Err(Error::Protocol(_))+ ));++ // Phone unlocks DND, brightness, and Elevated toggles.+ phone+ .node+ .update_power(+ PowerLevel::Elevated,+ vec![+ "media.control".into(),+ TOGGLES_READ.into(),+ TOGGLES_RINGER.into(),+ TOGGLES_VOLUME.into(),+ TOGGLES_FLASHLIGHT.into(),+ TOGGLES_DND.into(),+ TOGGLES_BRIGHTNESS.into(),+ TOGGLES_WIFI.into(),+ TOGGLES_BLUETOOTH.into(),+ ],+ )+ .await;+ wait_for(&mut pc, "toggles.wifi available", |e| match e {+ NodeEvent::Capabilities(m)+ if m.device == phone_id && m.state("toggles.wifi") == Some(FeatureState::Available) =>+ {+ Some(())+ }+ _ => None,+ })+ .await;++ with_timeout(+ "set ringer silent",+ pc.node.set_phone_toggle(+ phone_id,+ toggle_ids::RINGER.into(),+ PhoneToggleValue::Mode(ringer_modes::SILENT.into()),+ ),+ )+ .await+ .unwrap();+ with_timeout(+ "set dnd on",+ pc.node.set_phone_toggle(phone_id, toggle_ids::DND.into(), PhoneToggleValue::Bool(true)),+ )+ .await+ .unwrap();+ with_timeout(+ "set brightness",+ pc.node.set_phone_toggle(phone_id, toggle_ids::BRIGHTNESS.into(), PhoneToggleValue::Level(90)),+ )+ .await+ .unwrap();+ with_timeout(+ "set wifi off",+ pc.node.set_phone_toggle(phone_id, toggle_ids::WIFI.into(), PhoneToggleValue::Bool(false)),+ )+ .await+ .unwrap();++ let recorded = phone.platform.phone_toggles.lock().unwrap().clone();+ assert_eq!(+ recorded,+ vec![+ (toggle_ids::VOLUME.into(), PhoneToggleValue::Level(80)),+ (toggle_ids::RINGER.into(), PhoneToggleValue::Mode(ringer_modes::VIBRATE.into())),+ (toggle_ids::FLASHLIGHT.into(), PhoneToggleValue::Bool(true)),+ (toggle_ids::RINGER.into(), PhoneToggleValue::Mode(ringer_modes::SILENT.into())),+ (toggle_ids::DND.into(), PhoneToggleValue::Bool(true)),+ (toggle_ids::BRIGHTNESS.into(), PhoneToggleValue::Level(90)),+ (toggle_ids::WIFI.into(), PhoneToggleValue::Bool(false)),+ ]+ );++ // Phone pushes updated toggles state; PC receives it.+ let updated = PhoneToggles {+ dnd: true,+ ringer: ringer_modes::SILENT.into(),+ flashlight: Some(true),+ volume: 80,+ brightness: 90,+ wifi: false,+ bluetooth: true,+ };+ phone.node.toggles_changed(updated.clone()).await.unwrap();+ let got_updated = wait_for(&mut pc, "updated toggles", |e| match e {+ NodeEvent::PhoneToggles { device, toggles } if *device == phone_id && *toggles == updated => {+ Some(toggles.clone())+ }+ _ => None,+ })+ .await;+ assert_eq!(got_updated, updated);++ // Turning off the `toggles` device toggle on the phone refuses `phone.toggle.set`.+ phone.node.set_device_toggle(pc_id, "toggles", false).unwrap();+ assert!(matches!(+ pc.node.set_phone_toggle(phone_id, toggle_ids::VOLUME.into(), PhoneToggleValue::Level(50)).await,+ Err(Error::Denied)+ ));+}diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex e28ef11..0b081d9 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -474,6 +474,63 @@ pub enum Event {RemoteInputRequested {id: String,},+ /// A paired phone's quick settings state (PCs only).+ PhoneToggles {+ id: String,+ toggles: PhoneToggles,+ },+}++/// This phone's quick settings state (docs/protocol/toggles.md).+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]+pub struct PhoneToggles {+ pub dnd: bool,+ /// `"ring"`, `"vibrate"` or `"silent"`.+ pub ringer: String,+ /// `None` when the phone has no camera flash.+ pub flashlight: Option<bool>,+ /// Media volume, `0..=100`.+ pub volume: u8,+ /// Screen brightness, `0..=100`.+ pub brightness: u8,+ pub wifi: bool,+ pub bluetooth: bool,+}++impl From<core::PhoneToggles> for PhoneToggles {+ fn from(t: core::PhoneToggles) -> Self {+ PhoneToggles {+ dnd: t.dnd,+ ringer: t.ringer,+ flashlight: t.flashlight,+ volume: t.volume,+ brightness: t.brightness,+ wifi: t.wifi,+ bluetooth: t.bluetooth,+ }+ }+}++impl From<PhoneToggles> for core::PhoneToggles {+ fn from(t: PhoneToggles) -> Self {+ core::PhoneToggles {+ dnd: t.dnd,+ ringer: t.ringer,+ flashlight: t.flashlight,+ volume: t.volume,+ brightness: t.brightness,+ wifi: t.wifi,+ bluetooth: t.bluetooth,+ }+ }+}++/// The value to set for a phone quick setting (`phone.toggle.set`).+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]+pub enum PhoneToggleValue {+ Bool { on: bool },+ Level { level: u8 },+ Mode { mode: String },}/// What a mirroring video packet holds (docs/protocol/mirror.md).@@ -1253,6 +1310,9 @@ impl From<NodeEvent> for Event {NodeEvent::RemoteInputRequested { device } => {Event::RemoteInputRequested { id: device.to_string() }}+ NodeEvent::PhoneToggles { device, toggles } => {+ Event::PhoneToggles { id: device.to_string(), toggles: toggles.into() }+ }}}}@@ -1416,6 +1476,10 @@ pub trait Platform: Send + Sync {fn sms_send(&self, to: Vec<String>, body: String) -> bool;/// A PC asked for a message's attachment; null when it's gone.fn sms_part(&self, id: String) -> Option<SmsPartData>;+ /// A PC asked to change one of this phone's quick settings (`id`: `"dnd"`,+ /// `"ringer"`, `"flashlight"`, `"volume"`, `"brightness"`, `"wifi"`,+ /// `"bluetooth"`). False if the phone couldn't.+ fn set_phone_toggle(&self, id: String, value: PhoneToggleValue) -> bool;}/// Encrypts the device key at rest (Android: a Keystore key).@@ -1655,6 +1719,14 @@ impl core::Platform for PlatformAdapter {.map(|t| core::PhotoThumb { id: t.id, data: t.data }).collect())}+ fn set_phone_toggle(&self, id: &str, value: &core::PhoneToggleValue) -> Result<(), String> {+ let value = match value {+ core::PhoneToggleValue::Bool(on) => PhoneToggleValue::Bool { on: *on },+ core::PhoneToggleValue::Level(level) => PhoneToggleValue::Level { level: *level },+ core::PhoneToggleValue::Mode(mode) => PhoneToggleValue::Mode { mode: mode.clone() },+ };+ if self.0.set_phone_toggle(id.to_owned(), value) { Ok(()) } else { Err("the phone couldn't".into()) }+ }}struct KeyProtectorAdapter(Arc<dyn KeyProtector>);@@ -2161,6 +2233,14 @@ impl NectarlinkNode {self.run(async move { Ok(node.photo_taken(photo).await?) }).await}+ /// This phone's quick settings state (on startup and whenever any toggle+ /// changes): tells the PCs that show toggles (and are allowed them).+ pub async fn toggles_changed(&self, toggles: PhoneToggles) -> Result<()> {+ let node = self.node.clone();+ let toggles: core::PhoneToggles = toggles.into();+ self.run(async move { Ok(node.toggles_changed(toggles).await?) }).await+ }+/// Reconnects to PCs that aren't connected and syncs connected ones.pub async fn refresh(&self) {let node = self.node.clone();diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex d133800..bf49164 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -70,6 +70,8 @@ pub mod types {pub const MIRROR_APPS: &str = "mirror.apps";pub const REMOTE_CHECK: &str = "remote.check";pub const REMOTE_INPUT: &str = "remote.input";+ pub const PHONE_TOGGLES: &str = "phone.toggles";+ pub const PHONE_TOGGLE_SET: &str = "phone.toggle.set";}/// What kind of device this is.@@ -1934,6 +1936,111 @@ impl RemoteInput {}}+// ---- Phone toggles (docs/protocol/toggles.md) ----++/// Capability IDs for `phone.toggles` and `phone.toggle.set`.+pub mod toggles {+ pub const READ: &str = "toggles.read";+ pub const RINGER: &str = "toggles.ringer";+ pub const VOLUME: &str = "toggles.volume";+ pub const FLASHLIGHT: &str = "toggles.flashlight";+ pub const DND: &str = "toggles.dnd";+ pub const BRIGHTNESS: &str = "toggles.brightness";+ pub const WIFI: &str = "toggles.wifi";+ pub const BLUETOOTH: &str = "toggles.bluetooth";+ pub const SHOW: &str = "toggles.show";+}++/// Toggle IDs in `phone.toggle.set`.+pub mod toggle_ids {+ pub const DND: &str = "dnd";+ pub const RINGER: &str = "ringer";+ pub const FLASHLIGHT: &str = "flashlight";+ pub const VOLUME: &str = "volume";+ pub const BRIGHTNESS: &str = "brightness";+ pub const WIFI: &str = "wifi";+ pub const BLUETOOTH: &str = "bluetooth";+ pub const ALL: &[&str] = &[DND, RINGER, FLASHLIGHT, VOLUME, BRIGHTNESS, WIFI, BLUETOOTH];+}++/// Ringer modes for [`PhoneToggles::ringer`] and `phone.toggle.set` (`id = "ringer"`).+pub mod ringer_modes {+ pub const RING: &str = "ring";+ pub const VIBRATE: &str = "vibrate";+ pub const SILENT: &str = "silent";+}++/// Body of `phone.toggles` (`docs/protocol/toggles.md` §2.1): a phone's+/// current quick settings state.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhoneToggles {+ pub dnd: bool,+ /// `"ring"`, `"vibrate"` or `"silent"`.+ pub ringer: String,+ /// `None` when the phone has no flash unit.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub flashlight: Option<bool>,+ /// Media volume, `0..=100`.+ pub volume: u8,+ /// Screen brightness, `0..=100`.+ pub brightness: u8,+ pub wifi: bool,+ pub bluetooth: bool,+}++impl PhoneToggles {+ pub fn is_valid(&self) -> bool {+ matches!(self.ringer.as_str(), ringer_modes::RING | ringer_modes::VIBRATE | ringer_modes::SILENT)+ && self.volume <= 100+ && self.brightness <= 100+ }++ /// Validates `ringer` and clamps `volume` and `brightness` to `0..=100`.+ pub fn sanitized(mut self) -> Option<Self> {+ if !matches!(self.ringer.as_str(), ringer_modes::RING | ringer_modes::VIBRATE | ringer_modes::SILENT)+ {+ return None;+ }+ self.volume = self.volume.min(100);+ self.brightness = self.brightness.min(100);+ Some(self)+ }+}++/// A toggle value in [`PhoneToggleSet`].+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(untagged)]+pub enum PhoneToggleValue {+ Bool(bool),+ Level(u8),+ Mode(String),+}++/// Body of `phone.toggle.set` (`docs/protocol/toggles.md` §2.2).+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PhoneToggleSet {+ pub id: String,+ pub value: PhoneToggleValue,+}++impl PhoneToggleSet {+ /// Checks that `id` is a known toggle and `value` has the type and range+ /// that toggle accepts.+ pub fn is_valid(&self) -> bool {+ match (self.id.as_str(), &self.value) {+ (+ toggle_ids::DND | toggle_ids::FLASHLIGHT | toggle_ids::WIFI | toggle_ids::BLUETOOTH,+ PhoneToggleValue::Bool(_),+ ) => true,+ (toggle_ids::VOLUME | toggle_ids::BRIGHTNESS, PhoneToggleValue::Level(n)) => *n <= 100,+ (toggle_ids::RINGER, PhoneToggleValue::Mode(m)) => {+ matches!(m.as_str(), ringer_modes::RING | ringer_modes::VIBRATE | ringer_modes::SILENT)+ }+ _ => false,+ }+ }+}+#[cfg(test)]mod tests {use super::*;@@ -2354,4 +2461,69 @@ mod tests {let env = Envelope::new(types::REMOTE_INPUT, &slide).unwrap();assert_eq!(env.body::<RemoteInput>().unwrap(), slide);}++ #[test]+ fn phone_toggles_validate_and_round_trip() {+ let state = PhoneToggles {+ dnd: false,+ ringer: ringer_modes::RING.into(),+ flashlight: Some(true),+ volume: 65,+ brightness: 50,+ wifi: true,+ bluetooth: true,+ };+ assert!(state.is_valid());+ let env = Envelope::new(types::PHONE_TOGGLES, &state).unwrap();+ let back: PhoneToggles = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();+ assert_eq!(back, state);++ // Without flash hardware, `flashlight` is omitted on the wire.+ let no_flash = PhoneToggles { flashlight: None, ..state.clone() };+ let env = Envelope::new(types::PHONE_TOGGLES, &no_flash).unwrap();+ assert!(!format!("{:?}", env.b).contains("flashlight"));+ let back: PhoneToggles = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();+ assert_eq!(back, no_flash);++ // Invalid ringer mode is rejected; out-of-range volume/brightness clamp in sanitized().+ assert!(!PhoneToggles { ringer: "loud".into(), ..state.clone() }.is_valid());+ assert_eq!(PhoneToggles { ringer: "loud".into(), ..state.clone() }.sanitized(), None);+ assert!(!PhoneToggles { volume: 120, ..state.clone() }.is_valid());+ assert_eq!(PhoneToggles { volume: 120, brightness: 200, ..state }.sanitized().unwrap().volume, 100);++ // `phone.toggle.set` validation for every toggle ID and value kind.+ for id in [toggle_ids::DND, toggle_ids::FLASHLIGHT, toggle_ids::WIFI, toggle_ids::BLUETOOTH] {+ let set = PhoneToggleSet { id: id.into(), value: PhoneToggleValue::Bool(true) };+ assert!(set.is_valid(), "{id}");+ let env = Envelope::new(types::PHONE_TOGGLE_SET, &set).unwrap();+ assert_eq!(Envelope::from_cbor(&env.to_cbor()).unwrap().body::<PhoneToggleSet>().unwrap(), set);+ assert!(!PhoneToggleSet { id: id.into(), value: PhoneToggleValue::Level(1) }.is_valid());+ assert!(!PhoneToggleSet { id: id.into(), value: PhoneToggleValue::Mode("on".into()) }.is_valid());+ }+ for id in [toggle_ids::VOLUME, toggle_ids::BRIGHTNESS] {+ for level in [0, 50, 100] {+ let set = PhoneToggleSet { id: id.into(), value: PhoneToggleValue::Level(level) };+ assert!(set.is_valid());+ let env = Envelope::new(types::PHONE_TOGGLE_SET, &set).unwrap();+ assert_eq!(+ Envelope::from_cbor(&env.to_cbor()).unwrap().body::<PhoneToggleSet>().unwrap(),+ set+ );+ }+ assert!(!PhoneToggleSet { id: id.into(), value: PhoneToggleValue::Level(101) }.is_valid());+ assert!(!PhoneToggleSet { id: id.into(), value: PhoneToggleValue::Bool(true) }.is_valid());+ }+ for mode in [ringer_modes::RING, ringer_modes::VIBRATE, ringer_modes::SILENT] {+ let set =+ PhoneToggleSet { id: toggle_ids::RINGER.into(), value: PhoneToggleValue::Mode(mode.into()) };+ assert!(set.is_valid());+ let env = Envelope::new(types::PHONE_TOGGLE_SET, &set).unwrap();+ assert_eq!(Envelope::from_cbor(&env.to_cbor()).unwrap().body::<PhoneToggleSet>().unwrap(), set);+ }+ assert!(+ !PhoneToggleSet { id: toggle_ids::RINGER.into(), value: PhoneToggleValue::Mode("mute".into()) }+ .is_valid()+ );+ assert!(!PhoneToggleSet { id: "airplane".into(), value: PhoneToggleValue::Bool(true) }.is_valid());+ }}diff --git a/desktop/app/qml/Icons.qml b/desktop/app/qml/Icons.qmlindex 7770a0c..324996f 100644--- a/desktop/app/qml/Icons.qml+++ b/desktop/app/qml/Icons.qml@@ -64,4 +64,7 @@ QtObject {readonly property string download: "M12 3v12M7 10l5 5 5-5M5 20h14"readonly property string openExternal: "M14 4h6v6M20 4l-9 9M19 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h5"readonly property string video: "M4 6h11a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2zM17 10l5-3v10l-5-3"+ readonly property string flashlight: "M8 3h8l-2 5v11a2 2 0 0 1-4 0V8zM8 5.5h8M12 11v2"+ readonly property string bluetooth: "M6.5 6.5l11 11L12 22V2l5.5 5.5-11 11"+ readonly property string brightness: "M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"}diff --git a/desktop/app/qml/components/LockChip.qml b/desktop/app/qml/components/LockChip.qmlindex f5df06b..af212e5 100644--- a/desktop/app/qml/components/LockChip.qml+++ b/desktop/app/qml/components/LockChip.qml@@ -15,6 +15,8 @@ Rectangle {case "raisePower": return s.target === "elevated" ? qsTr("Elevated") : qsTr("Assist")case "grantPermission":return s.target === "notification_access" ? qsTr("Allow notification access on the phone")+ : s.target === "dnd_access" ? qsTr("Allow Do Not Disturb on the phone")+ : s.target === "write_settings" ? qsTr("Allow system settings on the phone"): qsTr("Allow it on the phone")case "enableAddon": return qsTr("Add-on")case "enablePath": return qsTr("Away mode")diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qmlindex 45620f0..b6a0658 100644--- a/desktop/app/qml/pages/HomePage.qml+++ b/desktop/app/qml/pages/HomePage.qml@@ -574,6 +574,205 @@ Item {}}}++ // Quick settings on the phone (toggles, ringer, volume, brightness).+ Card {+ id: phoneControls+ width: parent.width+ visible: home.online && state !== null+ property bool confirmWifiOff: false+ property var hoveredLockedFeature: null+ readonly property var state: {+ if (AppController.phoneTogglesRevision < 0)+ return null+ const raw = AppController.phoneToggles(home.deviceId)+ if (!raw || raw.length === 0)+ return null+ try {+ return JSON.parse(raw)+ } catch (e) {+ return null+ }+ }+ readonly property bool hasFlashlight: state !== null+ && state.flashlight !== undefined && state.flashlight !== null+ readonly property var dndFeature: home.feature("toggles.dnd")+ readonly property var flashlightFeature: home.feature("toggles.flashlight")+ readonly property var ringerFeature: home.feature("toggles.ringer")+ readonly property var volumeFeature: home.feature("toggles.volume")+ readonly property var brightnessFeature: home.feature("toggles.brightness")+ readonly property var wifiFeature: home.feature("toggles.wifi")+ readonly property var bluetoothFeature: home.feature("toggles.bluetooth")+ readonly property var activeLockFeature: {+ if (hoveredLockedFeature && hoveredLockedFeature.state === "locked")+ return hoveredLockedFeature+ if (wifiFeature.state === "locked")+ return wifiFeature+ if (dndFeature.state === "locked")+ return dndFeature+ return ({})+ }+ onVisibleChanged: if (!visible) confirmWifiOff = false++ Column {+ width: parent.width+ spacing: 12++ Txt { text: qsTr("Phone controls"); role: "label"; muted: true }++ Row {+ id: toggleRow+ width: parent.width+ spacing: 6+ readonly property int buttonCount: phoneControls.hasFlashlight ? 5 : 4+ readonly property real buttonWidth: (width - spacing * (buttonCount - 1)) / buttonCount++ QuickToggleButton {+ width: toggleRow.buttonWidth+ iconPath: Icons.moon+ shortTitle: qsTr("DND")+ label: qsTr("Do Not Disturb")+ active: phoneControls.state ? Boolean(phoneControls.state.dnd) : false+ feature: phoneControls.dndFeature+ onHoveredChanged: if (hovered && !available) phoneControls.hoveredLockedFeature = feature+ onClicked: AppController.setPhoneToggle(home.deviceId, "dnd", String(!active))+ }+ QuickToggleButton {+ visible: phoneControls.hasFlashlight+ width: toggleRow.buttonWidth+ iconPath: Icons.flashlight+ shortTitle: qsTr("Torch")+ label: qsTr("Flashlight")+ active: phoneControls.state !== null && phoneControls.state.flashlight === true+ feature: phoneControls.flashlightFeature+ onHoveredChanged: if (hovered && !available) phoneControls.hoveredLockedFeature = feature+ onClicked: AppController.setPhoneToggle(home.deviceId, "flashlight", String(!active))+ }+ QuickToggleButton {+ width: toggleRow.buttonWidth+ iconPath: Icons.wifi+ shortTitle: qsTr("Wi‑Fi")+ label: qsTr("Wi‑Fi")+ active: phoneControls.state ? Boolean(phoneControls.state.wifi) : false+ feature: phoneControls.wifiFeature+ onHoveredChanged: if (hovered && !available) phoneControls.hoveredLockedFeature = feature+ onClicked: {+ if (active)+ phoneControls.confirmWifiOff = true+ else+ AppController.setPhoneToggle(home.deviceId, "wifi", "true")+ }+ }+ QuickToggleButton {+ width: toggleRow.buttonWidth+ iconPath: Icons.bluetooth+ shortTitle: qsTr("BT")+ label: qsTr("Bluetooth")+ active: phoneControls.state ? Boolean(phoneControls.state.bluetooth) : false+ feature: phoneControls.bluetoothFeature+ onHoveredChanged: if (hovered && !available) phoneControls.hoveredLockedFeature = feature+ onClicked: AppController.setPhoneToggle(home.deviceId, "bluetooth", String(!active))+ }+ }++ LockChip {+ visible: label.length > 0+ feature: phoneControls.activeLockFeature+ maxWidth: parent.width+ }++ // Confirm before turning Wi-Fi off, since that can sever the link.+ Rectangle {+ width: parent.width+ height: wifiConfirmCol.height + 20+ visible: phoneControls.confirmWifiOff && phoneControls.state !== null && Boolean(phoneControls.state.wifi)+ radius: Theme.radiusMd+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHigh+ border.width: 1+ border.color: Theme.outlineVariant+ Column {+ id: wifiConfirmCol+ x: 12+ y: 10+ width: parent.width - 24+ spacing: 8+ Txt {+ width: parent.width+ role: "bodySmall"+ wrapMode: Text.WordWrap+ text: qsTr("Turning Wi‑Fi off on %1 will disconnect it if Wi‑Fi is how it reaches this PC.")+ .arg(home.name)+ }+ Row {+ anchors.right: parent.right+ spacing: 8+ Button {+ variant: "text"+ size: "sm"+ text: qsTr("Cancel")+ onClicked: phoneControls.confirmWifiOff = false+ }+ Button {+ variant: "tonal"+ size: "sm"+ text: qsTr("Turn off")+ onClicked: {+ phoneControls.confirmWifiOff = false+ AppController.setPhoneToggle(home.deviceId, "wifi", "false")+ }+ }+ }+ }+ }++ // Ringer mode segmented control.+ Column {+ width: parent.width+ spacing: 6+ Segmented {+ width: parent.width+ enabled: phoneControls.ringerFeature.state === "available"+ || phoneControls.ringerFeature.state === "partial"+ opacity: enabled ? 1 : 0.5+ options: [+ { value: "ring", label: qsTr("Ring") },+ { value: "vibrate", label: qsTr("Vibrate") },+ { value: "silent", label: qsTr("Silent") }+ ]+ value: phoneControls.state ? phoneControls.state.ringer : "ring"+ onPicked: (mode) => AppController.setPhoneToggle(home.deviceId, "ringer", mode)+ }+ LockChip {+ visible: phoneControls.ringerFeature.state === "locked" && label.length > 0+ feature: phoneControls.ringerFeature+ maxWidth: parent.width+ }+ }++ // Media volume slider.+ ToggleSlider {+ width: parent.width+ deviceId: home.deviceId+ toggleId: "volume"+ title: qsTr("Volume")+ iconPath: shownValue === 0 ? Icons.soundOff : Icons.speaker+ phoneValue: phoneControls.state ? phoneControls.state.volume : 0+ feature: phoneControls.volumeFeature+ }++ // Screen brightness slider.+ ToggleSlider {+ width: parent.width+ deviceId: home.deviceId+ toggleId: "brightness"+ title: qsTr("Brightness")+ iconPath: Icons.brightness+ phoneValue: phoneControls.state ? phoneControls.state.brightness : 0+ feature: phoneControls.brightnessFeature+ }+ }+ }+Card {width: parent.widthColumn {@@ -858,4 +1057,255 @@ Item {onClicked: tile.sideClicked()}}++ // Compact icon button for a phone quick toggle (DND, Flashlight, Wi-Fi, Bluetooth).+ component QuickToggleButton: FocusScope {+ id: qbtn+ property string iconPath+ property string shortTitle+ property string label+ property bool active: false+ property var feature: ({})+ readonly property bool available: feature.state === "available"+ readonly property alias hovered: qhover.hovered+ signal clicked++ height: 52+ activeFocusOnTab: available++ Accessible.role: Accessible.CheckBox+ Accessible.name: label+ Accessible.checked: active+ Accessible.onPressAction: if (qbtn.available) qbtn.clicked()+ Keys.onPressed: (event) => {+ if (qbtn.available && (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space)) {+ qbtn.clicked()+ event.accepted = true+ }+ }++ readonly property color fillColor: {+ if (active && available)+ return Theme.graphite ? Theme.surfaceContent : Theme.primary+ if (active && !available)+ return Theme.graphite ? Theme.surfaceContainerHigh : Theme.secondaryContainer+ return Theme.graphite ? "transparent" : Theme.surfaceContainerHigh+ }+ readonly property color contentColor: {+ if (active && available)+ return Theme.graphite ? Theme.surface : Theme.primaryContent+ if (active && !available)+ return Theme.graphite ? Theme.surfaceContent : Theme.secondaryContainerContent+ return available ? Theme.surfaceContent : Theme.surfaceContentVariant+ }++ Rectangle {+ anchors.fill: parent+ radius: Theme.radiusMd+ color: qbtn.fillColor+ border.width: Theme.focusVisible(qbtn) ? 2 : (Theme.graphite || (qbtn.active && !qbtn.available) ? 1 : 0)+ border.color: Theme.focusVisible(qbtn) ? Theme.primary : Theme.outlineVariant+ opacity: qbtn.available || qbtn.active ? 1 : 0.55+ scale: qtap.pressed && qbtn.available ? Theme.pressScale : 1+ Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }+ Behavior on color { ColorAnimation { duration: Theme.fadeFast } }++ Column {+ anchors.centerIn: parent+ width: parent.width - 4+ spacing: 3+ Icon {+ anchors.horizontalCenter: parent.horizontalCenter+ width: 17; height: 17+ path: qbtn.iconPath+ color: qbtn.contentColor+ }+ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ role: "caption"+ size: Theme.graphite ? 9 : 11+ font.letterSpacing: Theme.graphite ? 0 : (graphiteLabel ? Theme.labelStyle.tracking : spec.tracking) * size+ color: qbtn.contentColor+ text: qbtn.shortTitle+ elide: Text.ElideRight+ }+ }++ Icon {+ visible: !qbtn.available+ anchors.right: parent.right+ anchors.top: parent.top+ anchors.margins: 4+ width: 10; height: 10+ path: Icons.lock+ color: qbtn.contentColor+ opacity: 0.7+ }+ }++ HoverHandler { id: qhover; cursorShape: qbtn.available ? Qt.PointingHandCursor : Qt.ArrowCursor }+ TapHandler { id: qtap; enabled: qbtn.available; onTapped: qbtn.clicked() }+ }++ // Debounced 0..=100 slider for a phone setting (media volume, screen brightness).+ component ToggleSlider: Column {+ id: slider+ property string deviceId+ property string toggleId+ property string title+ property string iconPath+ property int phoneValue: 0+ property var feature: ({})+ readonly property bool available: feature.state === "available"+ property int dragValue: -1+ readonly property int shownValue: dragValue >= 0 ? dragValue : Math.max(0, Math.min(100, phoneValue))++ spacing: 4++ Timer {+ id: sendDebounce+ interval: 100+ onTriggered: if (slider.dragValue >= 0) {+ AppController.setPhoneToggle(slider.deviceId, slider.toggleId, String(slider.dragValue))+ }+ }+ Timer {+ id: settle+ interval: 400+ onTriggered: if (!dragArea.pressed) slider.dragValue = -1+ }++ Item {+ width: parent.width+ height: 20+ Row {+ anchors.verticalCenter: parent.verticalCenter+ spacing: 6+ Icon {+ anchors.verticalCenter: parent.verticalCenter+ width: 15; height: 15+ path: slider.iconPath+ color: slider.available ? Theme.surfaceContent : Theme.surfaceContentVariant+ }+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ role: "bodySmall"+ muted: !slider.available+ text: slider.title+ }+ }+ Txt {+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ role: "caption"+ muted: true+ text: qsTr("%1%").arg(slider.shownValue)+ }+ }++ FocusScope {+ id: barScope+ width: parent.width+ height: 18+ activeFocusOnTab: slider.available+ Accessible.role: Accessible.Slider+ Accessible.name: slider.title+ Accessible.description: qsTr("%1%").arg(slider.shownValue)+ Accessible.onPressAction: if (slider.available) {+ const next = slider.shownValue >= 80 ? 25 : slider.shownValue + 20+ slider.dragValue = next+ settle.restart()+ AppController.setPhoneToggle(slider.deviceId, slider.toggleId, String(next))+ }+ Keys.onPressed: (event) => {+ if (!slider.available) return+ if (event.key === Qt.Key_Left || event.key === Qt.Key_Down) {+ const next = Math.max(0, slider.shownValue - 5)+ slider.dragValue = next+ settle.restart()+ AppController.setPhoneToggle(slider.deviceId, slider.toggleId, String(next))+ event.accepted = true+ } else if (event.key === Qt.Key_Right || event.key === Qt.Key_Up) {+ const next = Math.min(100, slider.shownValue + 5)+ slider.dragValue = next+ settle.restart()+ AppController.setPhoneToggle(slider.deviceId, slider.toggleId, String(next))+ event.accepted = true+ }+ }++ readonly property real fraction: slider.shownValue / 100.0++ Rectangle {+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width+ height: 6+ radius: 3+ color: Theme.surfaceContainerHighest+ border.width: Theme.graphite ? 1 : 0+ border.color: Theme.outlineVariant+ opacity: slider.available ? 1 : 0.45++ Rectangle {+ width: parent.width * barScope.fraction+ height: parent.height+ radius: parent.radius+ color: slider.available+ ? (Theme.graphite ? Theme.surfaceContent : Theme.primary)+ : Theme.surfaceContentVariant+ }+ }++ Rectangle {+ visible: slider.available+ x: Math.max(0, Math.min(barScope.width - width, barScope.width * barScope.fraction - width / 2))+ anchors.verticalCenter: parent.verticalCenter+ width: 14; height: 14; radius: 7+ color: Theme.graphite ? Theme.surfaceContent : Theme.primary+ border.width: Theme.focusVisible(barScope) ? 2 : 0+ border.color: Theme.surface+ }++ MouseArea {+ id: dragArea+ anchors.fill: parent+ anchors.margins: -4+ enabled: slider.available+ hoverEnabled: true+ cursorShape: slider.available ? Qt.PointingHandCursor : Qt.ArrowCursor+ function levelAt(x) {+ return Math.round(Math.max(0, Math.min(1, (x - 4) / barScope.width)) * 100)+ }+ onPressed: (mouse) => {+ settle.stop()+ slider.dragValue = levelAt(mouse.x)+ if (!sendDebounce.running) sendDebounce.start()+ }+ onPositionChanged: (mouse) => {+ if (pressed) {+ slider.dragValue = levelAt(mouse.x)+ if (!sendDebounce.running) sendDebounce.start()+ }+ }+ onReleased: (mouse) => {+ sendDebounce.stop()+ const finalVal = levelAt(mouse.x)+ slider.dragValue = finalVal+ AppController.setPhoneToggle(slider.deviceId, slider.toggleId, String(finalVal))+ settle.restart()+ }+ onCanceled: {+ sendDebounce.stop()+ slider.dragValue = -1+ }+ }+ }++ LockChip {+ visible: !slider.available && label.length > 0 && slider.feature.action !== "enableToggle"+ feature: slider.feature+ maxWidth: parent.width+ }+ }}diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qmlindex 254ea4d..35c2fdb 100644--- a/desktop/app/qml/pages/SettingsPage.qml+++ b/desktop/app/qml/pages/SettingsPage.qml@@ -28,6 +28,7 @@ Item {recordings: qsTr("Voice recordings"),media: qsTr("Media playing on either device"),photos: qsTr("Photos"),+ toggles: qsTr("Phone controls"),pc_actions: qsTr("Lock and sleep this PC"),remote_input: qsTr("Control this PC's mouse and keyboard"),remote_files: qsTr("Browse this PC's files while away")diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rsindex da9e970..d8e00b8 100644--- a/desktop/app/src/bridge/app.rs+++ b/desktop/app/src/bridge/app.rs@@ -14,7 +14,7 @@ use cxx_qt::{CxxQtThread, CxxQtType, Threading};use cxx_qt_lib::{QHash, QHashPair_QString_QVariant, QList, QMap, QMapPair_QString_QVariant, QString, QVariant,};-use nectarlink_core::{DeviceId, Error, FeatureState, LinkState, features::Upgrade};+use nectarlink_core::{DeviceId, Error, FeatureState, LinkState, PhoneToggleValue, features::Upgrade};use crate::{core_host,@@ -50,6 +50,8 @@ pub mod qobject {#[qproperty(i32, caps_revision)]/// Bumped when a device toggle is changed from this PC.#[qproperty(i32, toggles_revision)]+ /// Bumped whenever a phone's quick settings toggles change.+ #[qproperty(i32, phone_toggles_revision)]/// Name of the device making this PC ring ("" when not ringing).#[qproperty(QString, ringing_from)]#[qproperty(bool, system_dark)]@@ -111,6 +113,14 @@ pub mod qobject {fn device_toggles(self: &AppController, device: &QString) -> QList_QVariant;#[qinvokable]fn set_device_toggle(self: Pin<&mut AppController>, device: &QString, name: &QString, on: bool);+ /// Latest quick settings toggles for a phone as JSON (`""` when unknown).+ #[qinvokable]+ fn phone_toggles(self: &AppController, device: &QString) -> QString;+ /// Changes one quick settings toggle on a phone (`id`: `"dnd"`,+ /// `"ringer"`, `"flashlight"`, `"volume"`, `"brightness"`, `"wifi"`,+ /// `"bluetooth"`).+ #[qinvokable]+ fn set_phone_toggle(self: Pin<&mut AppController>, device: &QString, id: &QString, value: &QString);/// Sends what's copied on this PC to a device.#[qinvokable]@@ -169,6 +179,7 @@ pub struct AppControllerRust {has_devices: bool,caps_revision: i32,toggles_revision: i32,+ phone_toggles_revision: i32,ringing_from: QString,system_dark: bool,reduce_motion: bool,@@ -295,7 +306,12 @@ impl cxx_qt::Initialize for qobject::AppController {*CONTROLLER.get_or_init(Mutex::default).lock().unwrap_or_else(|e| e.into_inner()) = Some(qt.clone());super::subscribe(qt.clone(),- Changes::STATUS | Changes::DEVICES | Changes::CAPABILITIES | Changes::RINGING | Changes::REMOTE,+ Changes::STATUS+ | Changes::DEVICES+ | Changes::CAPABILITIES+ | Changes::RINGING+ | Changes::REMOTE+ | Changes::TOGGLES,Self::refresh,);super::subscribe(qt.clone(), Changes::UPDATE, |object| {@@ -385,33 +401,35 @@ fn ring_device(device: DeviceId, on: bool) {impl qobject::AppController {fn refresh(mut self: Pin<&mut Self>) {let hub = &core_host::host().hub;- let (status, devices, ringing, online, caps_version, battery, remote_prompt, laser) = hub.read(|s| {- let ringing = s.ringing_from.and_then(|id| s.name_of(&id)).unwrap_or_default();- let remote_prompt = s.remote_prompt.map(|id| {- let name = s.name_of(&id).unwrap_or_else(|| id.short());- (id.to_string(), name)+ let (status, devices, ringing, online, caps_version, toggles_version, battery, remote_prompt, laser) =+ hub.read(|s| {+ let ringing = s.ringing_from.and_then(|id| s.name_of(&id)).unwrap_or_default();+ let remote_prompt = s.remote_prompt.map(|id| {+ let name = s.name_of(&id).unwrap_or_else(|| id.short());+ (id.to_string(), name)+ });+ let connected: Vec<_> =+ s.devices.iter().filter(|d| matches!(d.link, LinkState::Online { .. })).collect();+ // With one phone connected, the tray shows its battery.+ let battery = match connected.as_slice() {+ [one] => one.battery.as_ref().map(|b| {+ let charging = if b.charging { ", charging" } else { "" };+ format!("{} · {}%{charging}", one.info.name, b.level)+ }),+ _ => None,+ };+ (+ s.core_status(),+ s.devices.len(),+ ringing,+ connected.len(),+ s.matrices_version,+ s.toggles_version,+ battery,+ remote_prompt,+ s.laser,+ )});- let connected: Vec<_> =- s.devices.iter().filter(|d| matches!(d.link, LinkState::Online { .. })).collect();- // With one phone connected, the tray shows its battery.- let battery = match connected.as_slice() {- [one] => one.battery.as_ref().map(|b| {- let charging = if b.charging { ", charging" } else { "" };- format!("{} · {}%{charging}", one.info.name, b.level)- }),- _ => None,- };- (- s.core_status(),- s.devices.len(),- ringing,- connected.len(),- s.matrices_version,- battery,- remote_prompt,- s.laser,- )- });let (status_text, error) = match &status {CoreStatus::Starting => ("starting", String::new()),CoreStatus::Ready { device_id, name } => {@@ -440,6 +458,7 @@ impl qobject::AppController {}// Truncation is fine: QML only compares revisions for equality.self.as_mut().set_caps_revision(caps_version as i32);+ self.as_mut().set_phone_toggles_revision(toggles_version as i32);if let Some(tray) = self.rust().tray.as_ref() {tray.set_find_phone_enabled(devices > 0);@@ -556,6 +575,51 @@ impl qobject::AppController {self.as_mut().set_toggles_revision(revision);}+ pub fn phone_toggles(&self, device: &QString) -> QString {+ let Some(id) = super::parse_device(device) else { return QString::default() };+ let json = core_host::host()+ .hub+ .read(|s| s.toggles.get(&id).and_then(|t| serde_json::to_string(t).ok()))+ .unwrap_or_default();+ QString::from(&json)+ }++ pub fn set_phone_toggle(self: Pin<&mut Self>, device: &QString, id: &QString, value: &QString) {+ let (Some(device), Some(node)) = (super::parse_device(device), core_host::node()) else { return };+ let id = String::from(id);+ let raw = String::from(value);+ let parsed = match id.as_str() {+ "dnd" | "flashlight" | "wifi" | "bluetooth" => Some(PhoneToggleValue::Bool(raw == "true")),+ "volume" | "brightness" => raw.parse::<u8>().ok().map(|v| PhoneToggleValue::Level(v.min(100))),+ "ringer" => Some(PhoneToggleValue::Mode(raw)),+ _ => None,+ };+ let Some(val) = parsed else { return };+ // Optimistically update local state so buttons and sliders don't snap back while the RPC runs.+ core_host::host().hub.update(|s| {+ let Some(t) = s.toggles.get(&device).cloned() else { return Changes::NONE };+ let mut next = t;+ match (id.as_str(), &val) {+ ("dnd", PhoneToggleValue::Bool(on)) => next.dnd = *on,+ ("flashlight", PhoneToggleValue::Bool(on)) => next.flashlight = Some(*on),+ ("wifi", PhoneToggleValue::Bool(on)) => next.wifi = *on,+ ("bluetooth", PhoneToggleValue::Bool(on)) => next.bluetooth = *on,+ ("volume", PhoneToggleValue::Level(v)) => next.volume = *v,+ ("brightness", PhoneToggleValue::Level(v)) => next.brightness = *v,+ ("ringer", PhoneToggleValue::Mode(m)) => next.ringer.clone_from(m),+ _ => {}+ }+ s.set_toggles(device, Some(next))+ });+ core_host::spawn(async move {+ if let Err(e) = node.set_phone_toggle(device, id, val).await {+ let latest = node.phone_toggles(device);+ core_host::host().hub.update(|s| s.set_toggles(device, latest));+ show_message(describe(&e));+ }+ });+ }+pub fn check_for_updates(mut self: Pin<&mut Self>) {if self.update_busy {return;diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rsindex 705b2cd..4bfa0e4 100644--- a/desktop/app/src/core_host.rs+++ b/desktop/app/src/core_host.rs@@ -106,6 +106,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {nectarlink_core::MIRROR_LISTEN.into(),nectarlink_core::INPUT_INJECT.into(),nectarlink_core::RECORDER.into(),+ nectarlink_core::TOGGLES_SHOW.into(),];let node = match Node::start(config, platform).await {Ok(node) => node,@@ -132,6 +133,8 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {.filter(|d| !matches!(d.link, LinkState::Offline { last_seen: None })).filter_map(|d| node.capabilities(d.id).ok()).collect();+ let toggles: Vec<_> =+ devices.iter().filter_map(|d| node.phone_toggles(d.id).map(|t| (d.id, t))).collect();let status = CoreStatus::Ready { device_id: node.device_id(), name: this_device().name };let _ = host.node.set(node);host.hub.update(|s| {@@ -139,6 +142,9 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {for m in matrices {changes |= s.set_matrix(m);}+ for (id, t) in toggles {+ changes |= s.set_toggles(id, Some(t));+ }s.status = Some(status);changes |= Changes::STATUS | Changes::CAPABILITIES;changes@@ -166,7 +172,20 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {tracing::warn!(missed, "UI fell behind core events; resyncing");let devices =host.node.get().map(|n| n.paired_devices().unwrap_or_default()).unwrap_or_default();- host.hub.update(|s| s.set_devices(devices));+ let toggles: Vec<_> = host+ .node+ .get()+ .map(|n| {+ devices.iter().filter_map(|d| n.phone_toggles(d.id).map(|t| (d.id, t))).collect()+ })+ .unwrap_or_default();+ host.hub.update(|s| {+ let mut changes = s.set_devices(devices);+ for (id, t) in toggles {+ changes |= s.set_toggles(id, Some(t));+ }+ changes+ });}Err(RecvError::Closed) => return,}diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rsindex 44aa4a9..7af993b 100644--- a/desktop/app/src/state.rs+++ b/desktop/app/src/state.rs@@ -12,7 +12,8 @@ use std::{use nectarlink_core::{Battery, CapabilityMatrix, DeviceId, DeviceInfo, DiscoveredDevice, LinkState, MediaPlayer, NodeEvent,- Notification, PairedDevice, PairingEvent, PairingFailure, PowerLevel, Transfer, TransferState,+ Notification, PairedDevice, PairingEvent, PairingFailure, PhoneToggles, PowerLevel, Transfer,+ TransferState,};/// Which parts of the state changed, so listeners refresh only what they show.@@ -46,6 +47,8 @@ impl Changes {pub const PHOTOS: Changes = Changes(1 << 15);/// Remote input prompt or laser pointer overlay state.pub const REMOTE: Changes = Changes(1 << 16);+ /// A phone's quick settings toggles.+ pub const TOGGLES: Changes = Changes(1 << 17);pub fn is_empty(self) -> bool {self.0 == 0@@ -218,6 +221,10 @@ pub struct AppState {pub matrices: HashMap<DeviceId, CapabilityMatrix>,/// Bumped whenever `matrices` changes.pub matrices_version: u32,+ /// Latest quick settings toggles per paired phone.+ pub toggles: HashMap<DeviceId, PhoneToggles>,+ /// Bumped whenever `toggles` changes.+ pub toggles_version: u32,/// The device that asked this PC to ring, while it rings.pub ringing_from: Option<DeviceId>,/// Phone notifications, newest first.@@ -307,6 +314,10 @@ impl AppState {self.matrices_version = self.matrices_version.wrapping_add(1);changes |= Changes::CAPABILITIES;}+ if self.toggles.remove(id).is_some() {+ self.toggles_version = self.toggles_version.wrapping_add(1);+ changes |= Changes::TOGGLES;+ }if self.ringing_from == Some(*id) {self.ringing_from = None;changes |= Changes::RINGING;@@ -328,8 +339,9 @@ impl AppState {}NodeEvent::LinkChanged { device, link } => {let mut changes = self.update_device(device, |d| d.link = link.clone());- // A device that comes back sends what plays then.+ // A device that comes back sends what plays and its toggles then.if matches!(link, LinkState::Offline { .. }) {+ changes |= self.set_toggles(*device, None);changes |= self.set_media(*device, Vec::new());}changes@@ -341,6 +353,7 @@ impl AppState {NodeEvent::Battery { device, battery } => {self.update_device(device, |d| d.battery = Some(battery.clone()))}+ NodeEvent::PhoneToggles { device, toggles } => self.set_toggles(*device, Some(toggles.clone())),NodeEvent::Capabilities(matrix) => {if self.matrices.get(&matrix.device) == Some(matrix) {return Changes::NONE;@@ -641,6 +654,23 @@ impl AppState {Changes::CAPABILITIES}+ pub fn set_toggles(&mut self, device: DeviceId, toggles: Option<PhoneToggles>) -> Changes {+ let changed = match toggles {+ Some(t) if self.toggles.get(&device) == Some(&t) => false,+ Some(t) => {+ self.toggles.insert(device, t);+ true+ }+ None => self.toggles.remove(&device).is_some(),+ };+ if changed {+ self.toggles_version = self.toggles_version.wrapping_add(1);+ Changes::TOGGLES+ } else {+ Changes::NONE+ }+ }+pub fn set_pairing(&mut self, next: PairingView) -> Changes {if self.pairing == next {return Changes::NONE;@@ -1006,4 +1036,41 @@ mod tests {s.set_app_rule(&app, AppRule::Show);assert!(s.app_rules.is_empty(), "the default isn't stored");}++ #[test]+ fn phone_toggles_follow_events_and_clear_on_offline_or_unpair() {+ let mut s = AppState::default();+ let phone = DeviceId([1; 32]);+ s.apply(&NodeEvent::DeviceAdded(paired(1, 10)));+ let online = LinkState::Online { path: ConnectionPath::Lan, rtt_ms: 4 };+ s.apply(&NodeEvent::LinkChanged { device: phone, link: online });++ let toggles = PhoneToggles {+ dnd: false,+ ringer: "ring".into(),+ flashlight: Some(false),+ volume: 60,+ brightness: 70,+ wifi: true,+ bluetooth: true,+ };+ assert_eq!(+ s.apply(&NodeEvent::PhoneToggles { device: phone, toggles: toggles.clone() }),+ Changes::TOGGLES+ );+ assert_eq!(s.toggles.get(&phone), Some(&toggles));+ assert_eq!(+ s.apply(&NodeEvent::PhoneToggles { device: phone, toggles: toggles.clone() }),+ Changes::NONE+ );++ let offline = LinkState::Offline { last_seen: Some(100) };+ let changes = s.apply(&NodeEvent::LinkChanged { device: phone, link: offline });+ assert!(changes.intersects(Changes::TOGGLES));+ assert!(!s.toggles.contains_key(&phone));++ s.apply(&NodeEvent::PhoneToggles { device: phone, toggles });+ assert!(s.apply(&NodeEvent::DeviceRemoved(phone)).intersects(Changes::TOGGLES));+ assert!(s.toggles.is_empty());+ }}diff --git a/docs/PLAN.md b/docs/PLAN.mdindex 13a5fa8..28bfae1 100644--- a/docs/PLAN.md+++ b/docs/PLAN.md@@ -205,7 +205,7 @@ current Android. Talking through the PC comes with the HFP item above.| Type on the phone with the PC keyboard (without mirroring) | P1 🟣 || **Deck**: the phone becomes a Stream-Deck-style macro pad for the PC with live tiles: mic mute, media, app launchers, scripts, OBS scenes, window switching, multiple pages, haptic feedback | P1 🟢 || **Flow**: move the PC mouse off the screen edge onto the phone/tablet and back, with clipboard following | P2 🟣 |-| Phone toggles from PC: Wi-Fi, BT, DND, ringer, flashlight, brightness | P1 (partly 🟣) |+| Phone toggles from PC: Wi-Fi, BT, DND, ringer, flashlight, volume, brightness ✅ (the hotspot has no shell command to switch it; see Instant Hotspot) | P1 (partly 🟣) || PC actions from phone: lock, sleep, shutdown, mute, custom commands/scripts | P0 (lock/sleep), P1 (custom, off by default) || Wake-on-LAN | P1 || **Unlock PC with phone fingerprint**: the PC lock screen offers "Unlock with phone" → the phone shows a biometric prompt → a signed challenge unlocks Windows. Built as a Windows credential provider. Keys live in Android Keystore (StrongBox where available) and are bound to biometrics. Works only when paired and nearby (BLE proximity + LAN). Rate-limited, revocable, and **external security review before release** | P2 (dedicated workstream) |diff --git a/docs/architecture/capabilities.md b/docs/architecture/capabilities.mdindex 42e295e..c2f1137 100644--- a/docs/architecture/capabilities.md+++ b/docs/architecture/capabilities.md@@ -121,8 +121,8 @@ the OS (`android` → phone, `windows`/`macos` → desktop).## Per-device toggles`notifications`, `messages`, `calls`, `contacts`, `clipboard`, `files`,-`media`, `photos`, `recordings`, `pc_actions`, `mirroring` (on by default) and-`remote_input`, `remote_files` (off by default). Toggles are this+`media`, `photos`, `recordings`, `toggles`, `pc_actions`, `mirroring` (on by+default) and `remote_input`, `remote_files` (off by default). Toggles are thisdevice's policy for that peer and are stored locally, so a feature the PCuser switched off is Locked on the PC while the phone may still show it asAvailable. Everything else in the matrix is identical on both devices.diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.mdindex 678be26..ddfd437 100644--- a/docs/protocol/capabilities.md+++ b/docs/protocol/capabilities.md@@ -51,6 +51,14 @@ capability is missing.| `mirror.virtual_display` | Runs apps on displays of their own, shown in windows on the PC ([mirroring](mirror.md)) | Elevated, Android 11+ || `mirror.audio` | Streams all audio while mirrored | Elevated || `mirror.audio.playback` | Streams audio from apps that allow playback capture | app update |+| `toggles.read` | Shares quick settings state ([toggles](toggles.md)) | app update |+| `toggles.ringer` | Changes the ringer mode between `ring` and `vibrate` ([toggles](toggles.md)) | app update |+| `toggles.volume` | Changes the media volume ([toggles](toggles.md)) | app update |+| `toggles.flashlight` | Turns the flashlight on or off ([toggles](toggles.md)) | hardware flash unit |+| `toggles.dnd` | Turns Do Not Disturb on or off and sets the ringer to `silent` ([toggles](toggles.md)) | Do Not Disturb access or Elevated |+| `toggles.brightness` | Changes the screen brightness ([toggles](toggles.md)) | Modify system settings or Elevated |+| `toggles.wifi` | Turns Wi-Fi on or off ([toggles](toggles.md)) | Elevated |+| `toggles.bluetooth` | Turns Bluetooth on or off ([toggles](toggles.md)) | Elevated || `camera.stream` | Streams a camera for webcam use | camera permission |## Desktop@@ -62,6 +70,7 @@ capability is missing.| `call.show` | Shows a phone's calls, recent calls and dialer ([calls](calls.md)) | app update || `contacts.show` | Shows a phone's contacts ([contacts](contacts.md)) | app update || `sms.show` | Shows a phone's text messages ([messages](sms.md)) | app update |+| `toggles.show` | Shows a phone's quick settings and sends toggle changes ([toggles](toggles.md)) | app update || `mirror.view` | Shows a phone's screen ([mirroring](mirror.md)) | app update || `mirror.listen` | Plays a mirrored phone's sound ([mirroring](mirror.md)) | app update || `files.browse` | Lets a paired phone browse and fetch its files | app update |diff --git a/docs/protocol/toggles.md b/docs/protocol/toggles.mdnew file mode 100644index 0000000..17e8ef2--- /dev/null+++ b/docs/protocol/toggles.md@@ -0,0 +1,82 @@+# Phone toggles service (protocol v0)++> Status: **draft.** Builds on [protocol v0](v0.md); breaking changes are+> allowed until v1. License: CC BY 4.0.++A phone shares its quick settings state with paired PCs, and a PC can+change the settings the phone's Power Level and permissions allow. Settings+that cannot be changed right now are still shown read-only on the PC with+the capability matrix's reason for what unlocks them.++## 1. Capabilities++| ID | Offered by | Needs | Meaning |+|---|---|---|---|+| `toggles.read` | phone | Basic | Shares its quick settings state (`phone.toggles`) |+| `toggles.ringer` | phone | Basic | Changes the ringer mode between `ring` and `vibrate` (`silent` also needs `toggles.dnd`) |+| `toggles.volume` | phone | Basic | Changes the media volume (`0..=100`) |+| `toggles.flashlight` | phone | Basic | Turns the flashlight on or off (only on phones with a flash unit) |+| `toggles.dnd` | phone | Basic + Do Not Disturb access (or Elevated) | Turns Do Not Disturb on or off and sets the ringer to `silent` |+| `toggles.brightness` | phone | Basic + Modify system settings (or Elevated) | Changes the screen brightness (`0..=100`) |+| `toggles.wifi` | phone | Elevated | Turns Wi-Fi on or off |+| `toggles.bluetooth` | phone | Elevated | Turns Bluetooth on or off |+| `toggles.show` | desktop | — | Shows a phone's controls and sends `phone.toggle.set` requests |++A phone sends `phone.toggles` only to desktops that offer `toggles.show`,+and only while both devices allow the `toggles` device toggle (on by+default).++## 2. Messages++All on the control stream.++```+t = "phone.toggles" b = PhoneToggles // no reply+t = "phone.toggle.set" id = n b = { id: text, value: Value }+t = "ok" re = n+```++### 2.1 `phone.toggles`++Sent by the phone when a session starts, whenever any toggle changes on the+phone (debounced), and when the `toggles` device toggle is turned back on.++```+PhoneToggles = {+ dnd: bool, // Do Not Disturb is on+ ringer: text, // "ring" | "vibrate" | "silent"+ flashlight?: bool, // omitted when the phone has no flash unit+ volume: uint, // media volume, 0..=100+ brightness: uint, // screen brightness, 0..=100+ wifi: bool, // Wi-Fi is on+ bluetooth: bool, // Bluetooth is on+}+```++### 2.2 `phone.toggle.set`++Asks the phone to change one toggle:++| `id` | `value` | Required phone capability |+|---|---|---|+| `"dnd"` | `bool` | `toggles.dnd` |+| `"ringer"` | `"ring"` \| `"vibrate"` \| `"silent"` | `toggles.ringer` (and `toggles.dnd` for `"silent"`) |+| `"flashlight"` | `bool` | `toggles.flashlight` |+| `"volume"` | `uint` (`0..=100`) | `toggles.volume` |+| `"brightness"` | `uint` (`0..=100`) | `toggles.brightness` |+| `"wifi"` | `bool` | `toggles.wifi` |+| `"bluetooth"` | `bool` | `toggles.bluetooth` |++Errors:+- `BAD_MESSAGE` when `id` is unknown or `value` has the wrong type or is out of range (`> 100` for `volume`/`brightness`, or an unknown ringer mode).+- `UNSUPPORTED` when the phone does not offer the capability for `id` (or `toggles.dnd` when setting `ringer` to `"silent"`, or has no flash unit for `flashlight`).+- `DENIED` when the user turned the `toggles` device toggle off for the peer.+- `INTERNAL` when the platform call fails.++## 3. Rules++- **Confirm turning Wi-Fi off.** Turning Wi-Fi off from the PC can sever the+ LAN connection between the PC and the phone; the PC UI confirms with the+ user before sending `phone.toggle.set { id: "wifi", value: false }`.+- **Debouncing.** Continuous sliders (`volume`, `brightness`) are debounced+ by the sender so dragging a slider does not flood the control stream.