Skip to content

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

Calls on the PC: see who's calling, answer, decline or silence

Bee580370531777
diff --git a/README.md b/README.md
index 706c288..2c7a613 100644
--- a/README.md
+++ b/README.md
@@ -89,6 +89,9 @@ place and tested; the user-facing features of Phase 1 come next.
on the phone, share them from any app or pick them in Nectarlink. They land in `Downloads\Nectarlink` on the PC and
`Download/Nectarlink` on the phone, with progress, cancelling, and transfers
that pick up where they left off after a dropped connection.
+- **Calls**: see who's calling on the PC (with the contact's name and
+ photo), and answer, decline or silence it from there; the call itself
+ stays on the phone. Calls nobody answered show as missed.
- **New photos and screenshots** from the phone pop up on the PC with a
preview: save them to Downloads or copy them, ready to paste.
- **Media** both ways: what plays on the phone shows on the PC, in the app and
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 265f2c5..6c1271a 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -21,6 +21,12 @@
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<!-- Installing its own updates from GitHub releases (the user allows it once). -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
+ <!-- Calls, shown on paired PCs, with the caller's number and contact
+ (asked for in the app). The call itself stays on the phone. -->
+ <uses-permission android:name="android.permission.READ_PHONE_STATE" />
+ <uses-permission android:name="android.permission.READ_CALL_LOG" />
+ <uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
+ <uses-permission android:name="android.permission.READ_CONTACTS" />
<!-- New photos and screenshots, shown on paired PCs (asked for in the app). -->
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/calls/PhoneCalls.kt b/android/app/src/main/kotlin/app/nectarlink/android/calls/PhoneCalls.kt
new file mode 100644
index 0000000..c335f61
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/calls/PhoneCalls.kt
@@ -0,0 +1,268 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.calls
+
+import android.Manifest
+import android.annotation.SuppressLint
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import android.content.pm.PackageManager
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.media.AudioManager
+import android.net.Uri
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import android.provider.CallLog
+import android.provider.ContactsContract
+import android.telecom.TelecomManager
+import android.telephony.TelephonyManager
+import android.util.Log
+import androidx.core.content.ContextCompat
+import app.nectarlink.core.Call
+import app.nectarlink.core.CallCommand
+import app.nectarlink.core.CallPhase
+import java.io.ByteArrayOutputStream
+import java.util.concurrent.Executors
+
+/**
+ * The phone's calls, for PCs (docs/protocol/calls.md): follows the call
+ * state while the app runs, and answers, declines or silences a ringing
+ * call when a PC asks. The call's audio stays on the phone.
+ */
+internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unit) {
+ private val context = context.applicationContext
+ private val main = Handler(Looper.getMainLooper())
+ /** Contact lookups and reports, in order, off the main thread. */
+ private val worker = Executors.newSingleThreadExecutor()
+ private var receiver: BroadcastReceiver? = null
+
+ /** The call in progress (changed on the main thread, read by PCs' requests). */
+ @Volatile
+ private var current: Tracked? = null
+
+ private data class Tracked(
+ val id: String,
+ val incoming: Boolean,
+ var number: String?,
+ var answered: Boolean = false,
+ /** Declined from a PC: not a missed call. */
+ var declined: Boolean = false,
+ )
+
+ fun start() {
+ if (receiver != null || !canFollow(context)) return
+ receiver = object : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ val state = intent.getStringExtra(TelephonyManager.EXTRA_STATE) ?: return
+ // Only sent with the call log permission; a second broadcast
+ // carries it when there is one.
+ @Suppress("DEPRECATION")
+ val number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)
+ stateChanged(state, number?.takeIf { it.isNotBlank() })
+ }
+ }.also {
+ ContextCompat.registerReceiver(
+ context,
+ it,
+ IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED),
+ // A system broadcast: other apps can't send it here.
+ ContextCompat.RECEIVER_NOT_EXPORTED,
+ )
+ }
+ }
+
+ fun stop() {
+ receiver?.let { runCatching { context.unregisterReceiver(it) } }
+ receiver = null
+ current = null
+ }
+
+ private fun stateChanged(state: String, number: String?) {
+ val call = current
+ when (state) {
+ TelephonyManager.EXTRA_STATE_RINGING -> when {
+ call == null -> {
+ val tracked = Tracked(id = System.currentTimeMillis().toString(), incoming = true, number = number)
+ current = tracked
+ report(tracked, CallPhase.RINGING, withContact = true)
+ }
+ // The same call again, now with its number.
+ call.number == null && number != null && !call.answered -> {
+ call.number = number
+ report(call, CallPhase.RINGING, withContact = true)
+ }
+ }
+ TelephonyManager.EXTRA_STATE_OFFHOOK -> when {
+ call == null -> {
+ // Calling out.
+ val tracked = Tracked(id = System.currentTimeMillis().toString(), incoming = false, number = number, answered = true)
+ current = tracked
+ report(tracked, CallPhase.ACTIVE, withContact = false)
+ }
+ !call.answered -> {
+ call.answered = true
+ report(call, CallPhase.ACTIVE, withContact = false)
+ }
+ }
+ TelephonyManager.EXTRA_STATE_IDLE -> if (call != null) {
+ current = null
+ restoreRinger()
+ if (call.incoming && !call.answered && !call.declined) {
+ // Missed, or turned down on the phone: the call log knows,
+ // once it's written.
+ main.postDelayed({ report(call, CallPhase.ENDED, withContact = true, missedCheck = true) }, LOG_DELAY_MS)
+ } else {
+ report(call, CallPhase.ENDED, withContact = false)
+ }
+ }
+ }
+ }
+
+ private fun report(call: Tracked, phase: CallPhase, withContact: Boolean, missedCheck: Boolean = false) {
+ // A snapshot: the call may change while this waits its turn.
+ val number = call.number
+ val incoming = call.incoming
+ worker.execute { send(call.id, phase, incoming, number, withContact, missedCheck) }
+ }
+
+ private fun send(id: String, phase: CallPhase, incoming: Boolean, number: String?, withContact: Boolean, missedCheck: Boolean) {
+ val (name, photo) = if (withContact) contact(number) else null to null
+ val missed = missedCheck && wasMissed()
+ onChange(
+ Call(
+ id = id,
+ state = phase,
+ incoming = incoming,
+ number = number,
+ name = name,
+ photo = photo.takeIf { phase == CallPhase.RINGING },
+ missed = missed,
+ ),
+ )
+ }
+
+ /** The contact's name and photo for a number, when allowed and known. */
+ private fun contact(number: String?): Pair<String?, ByteArray?> {
+ if (number == null || !granted(context, Manifest.permission.READ_CONTACTS)) return null to null
+ return runCatching {
+ val uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number))
+ val columns = arrayOf(ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI)
+ context.contentResolver.query(uri, columns, null, null, null)?.use { cursor ->
+ if (!cursor.moveToFirst()) return@use null to null
+ val photo = cursor.getString(1)?.let { photoBytes(Uri.parse(it)) }
+ cursor.getString(0) to photo
+ } ?: (null to null)
+ }.getOrElse {
+ Log.i(TAG, "no contact for a call", it)
+ null to null
+ }
+ }
+
+ /** A JPEG of at most 64 KB. */
+ private fun photoBytes(uri: Uri): ByteArray? {
+ val bitmap = context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it) } ?: return null
+ return try {
+ generateSequence(90) { it - 15 }.takeWhile { it >= 45 }
+ .map { quality -> ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.JPEG, quality, it) }.toByteArray() }
+ .firstOrNull { it.size <= MAX_PHOTO_BYTES }
+ } finally {
+ bitmap.recycle()
+ }
+ }
+
+ /** Whether the latest call in the log is a missed one (not turned down or blocked). */
+ @SuppressLint("MissingPermission")
+ private fun wasMissed(): Boolean {
+ if (!granted(context, Manifest.permission.READ_CALL_LOG)) return true
+ return runCatching {
+ context.contentResolver.query(
+ CallLog.Calls.CONTENT_URI.buildUpon().appendQueryParameter(CallLog.Calls.LIMIT_PARAM_KEY, "1").build(),
+ arrayOf(CallLog.Calls.TYPE),
+ null,
+ null,
+ "${CallLog.Calls.DATE} DESC",
+ )?.use { if (it.moveToFirst()) it.getInt(0) == CallLog.Calls.MISSED_TYPE else true } ?: true
+ }.getOrDefault(true)
+ }
+
+ /** Runs what a PC asked; false if the phone couldn't. */
+ @SuppressLint("MissingPermission")
+ fun command(id: String, command: CallCommand): Boolean {
+ val call = current?.takeIf { it.id == id } ?: return false
+ if (!granted(context, Manifest.permission.ANSWER_PHONE_CALLS)) return false
+ val telecom = context.getSystemService(TelecomManager::class.java) ?: return false
+ return runCatching {
+ when (command) {
+ // Deprecated for dialer apps, which get the call directly;
+ // still how any other app answers one.
+ @Suppress("DEPRECATION")
+ CallCommand.ANSWER -> telecom.acceptRingingCall()
+ CallCommand.DECLINE -> {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return false
+ call.declined = !call.answered
+ @Suppress("DEPRECATION")
+ if (!telecom.endCall()) return false
+ }
+ CallCommand.SILENCE -> silence(telecom)
+ }
+ true
+ }.getOrElse {
+ Log.w(TAG, "a call action failed", it)
+ false
+ }
+ }
+
+ private var mutedRinger = false
+
+ @SuppressLint("MissingPermission")
+ private fun silence(telecom: TelecomManager) {
+ // Telecom's own silencing needs a permission only system apps get on
+ // some versions; muting the ring stream for this call does the same.
+ try {
+ telecom.silenceRinger()
+ } catch (_: SecurityException) {
+ val audio = context.getSystemService(AudioManager::class.java)
+ audio.adjustStreamVolume(AudioManager.STREAM_RING, AudioManager.ADJUST_MUTE, 0)
+ mutedRinger = true
+ }
+ }
+
+ private fun restoreRinger() {
+ if (!mutedRinger) return
+ mutedRinger = false
+ runCatching {
+ context.getSystemService(AudioManager::class.java).adjustStreamVolume(AudioManager.STREAM_RING, AudioManager.ADJUST_UNMUTE, 0)
+ }
+ }
+
+ companion object {
+ private const val TAG = "PhoneCalls"
+ private const val MAX_PHOTO_BYTES = 64 * 1024
+ /** How long the call log takes to have the call that just ended. */
+ private const val LOG_DELAY_MS = 1500L
+
+ /** Following calls, with numbers, contact names, and answering. */
+ val permissions: Array<String> = arrayOf(
+ Manifest.permission.READ_PHONE_STATE,
+ Manifest.permission.READ_CALL_LOG,
+ Manifest.permission.ANSWER_PHONE_CALLS,
+ Manifest.permission.READ_CONTACTS,
+ )
+
+ private fun granted(context: Context, permission: String) =
+ ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
+
+ /** Whether the app can follow calls at all. */
+ fun canFollow(context: Context) = granted(context, Manifest.permission.READ_PHONE_STATE)
+
+ /** Whether it can answer and decline them (declining needs Android 9). */
+ fun canControl(context: Context) =
+ canFollow(context) && granted(context, Manifest.permission.ANSWER_PHONE_CALLS)
+
+ /** Whether everything the card asks for is granted. */
+ fun hasAll(context: Context) = permissions.all { granted(context, it) }
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
index 268c945..a9e9583 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
@@ -16,6 +16,7 @@ import app.nectarlink.android.files.ReceivedFiles
import app.nectarlink.android.files.TransferNotifications
import app.nectarlink.android.R
import app.nectarlink.android.notifications.NotificationListener
+import app.nectarlink.android.calls.PhoneCalls
import app.nectarlink.android.photos.RecentPhotos
import app.nectarlink.core.Event
import app.nectarlink.core.EventListener
@@ -58,8 +59,17 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
private val phoneMedia = PhoneMedia(this.context) { players ->
notificationOps.trySend { it.mediaChanged(players) }
}
- private val platform = PhonePlatform(this.context, ringer, phoneMedia) { pc, url ->
- LinkNotifications.show(this.context, _state.value.nameOf(pc).orEmpty(), url)
+ private val platform = PhonePlatform(
+ this.context,
+ ringer,
+ phoneMedia,
+ onLink = { pc, url -> LinkNotifications.show(this.context, _state.value.nameOf(pc).orEmpty(), url) },
+ onCall = { id, command -> calls.command(id, command) },
+ )
+ private val calls = PhoneCalls(this.context) { call ->
+ notificationOps.trySend { node ->
+ runCatching { node.callChanged(call) }.onFailure { Log.i(TAG, "a call wasn't reported", it) }
+ }
}
private val photos = RecentPhotos(this.context) { photo ->
notificationOps.trySend { node ->
@@ -133,9 +143,12 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
battery.start()
network.start()
}
- _state.update { it.copy(photoAccess = RecentPhotos.hasAccess(context)) }
+ _state.update { it.copy(photoAccess = RecentPhotos.hasAccess(context), callAccess = PhoneCalls.hasAll(context)) }
started.updatePower(PowerLevel.BASIC, capabilities(NotificationListener.hasAccess(context)))
- scope.launch(Dispatchers.Main) { if (_state.value.photoAccess) photos.start() }
+ scope.launch(Dispatchers.Main) {
+ if (_state.value.photoAccess) photos.start()
+ calls.start()
+ }
scope.launch {
for (op in notificationOps) {
runCatching { op(started) }.onFailure { Log.w(TAG, "notification update failed", it) }
@@ -176,13 +189,23 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
val granted = NotificationListener.hasAccess(context)
val unrestricted = BackgroundAccess.isUnrestricted(context)
val photoAccess = RecentPhotos.hasAccess(context)
+ val callAccess = PhoneCalls.hasAll(context)
val photosChanged = photoAccess != _state.value.photoAccess
- _state.update { it.copy(notificationAccess = granted, backgroundUnrestricted = unrestricted, photoAccess = photoAccess) }
+ val callsChanged = callAccess != _state.value.callAccess
+ _state.update {
+ it.copy(
+ notificationAccess = granted,
+ backgroundUnrestricted = unrestricted,
+ photoAccess = photoAccess,
+ callAccess = callAccess,
+ )
+ }
if (granted && NotificationListener.instance == null) {
NotificationListenerService.requestRebind(NotificationListener.component(context))
}
- if (photosChanged && node != null) {
+ if ((photosChanged || callsChanged) && node != null) {
if (photoAccess) photos.start() else photos.stop()
+ if (PhoneCalls.canFollow(context)) calls.start() else calls.stop()
notificationOps.trySend { it.updatePower(PowerLevel.BASIC, capabilities(_state.value.notificationAccess)) }
}
}
@@ -311,7 +334,9 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
private fun capabilities(notificationAccess: Boolean): List<String> =
CLIPBOARD_CAPABILITIES +
(if (notificationAccess) NOTIFICATION_CAPABILITIES + MEDIA_CAPABILITIES else emptyList()) +
- (if (_state.value.photoAccess) PHOTO_CAPABILITIES else emptyList())
+ (if (_state.value.photoAccess) PHOTO_CAPABILITIES else emptyList()) +
+ (if (PhoneCalls.canFollow(context)) listOf("call.state") else emptyList()) +
+ (if (PhoneCalls.canControl(context)) listOf("call.control") else emptyList())
// ---- Pairing ----
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.kt
index a1d8428..9eba398 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
@@ -62,6 +62,8 @@ data class CoreState(
val ringingFrom: String? = null,
/** Whether the user let Nectarlink read notifications (to mirror them). */
val notificationAccess: Boolean = false,
+ /** Whether the user let Nectarlink follow and answer calls (to show them on PCs). */
+ val callAccess: Boolean = false,
/** Whether the user let Nectarlink see the phone's photos (to show new ones on PCs). */
val photoAccess: Boolean = false,
/** Whether Android lets Nectarlink run unrestricted in the background. */
@@ -110,8 +112,8 @@ 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.
- is Event.PhotoAdded -> this
+ // PCs only: phones announce their own photos and calls.
+ is Event.PhotoAdded, is Event.CallChanged -> this
}
private fun withTransfer(transfer: Transfer): List<Transfer> {
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt
index c99e3d7..a5177a6 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
@@ -12,6 +12,7 @@ import app.nectarlink.android.clipboard.PhoneClipboard
import app.nectarlink.android.notifications.NotificationListener
import app.nectarlink.android.media.PhoneMedia
import app.nectarlink.android.photos.RecentPhotos
+import app.nectarlink.core.CallCommand
import app.nectarlink.core.FileToSend
import app.nectarlink.core.MediaAction
import app.nectarlink.core.NotificationFailure
@@ -27,6 +28,8 @@ internal class PhonePlatform(
private val media: PhoneMedia,
/** Shows a link a PC sent: (PC's ID, link) → shown. */
private val onLink: (String, String) -> Boolean,
+ /** Answers, declines or silences a call: (call ID, command) → done. */
+ private val onCall: (String, CallCommand) -> Boolean,
) : Platform {
private val context = context.applicationContext
@@ -46,6 +49,8 @@ internal class PhonePlatform(
override fun openPhoto(id: String): FileToSend? = RecentPhotos.open(context, id)
+ override fun callCommand(id: String, command: CallCommand): Boolean = onCall(id, command)
+
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/ui/home/HomeScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
index 21ebe49..76fc6f8 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
@@ -51,6 +51,7 @@ import app.nectarlink.android.core.BackgroundAccess
import app.nectarlink.android.core.CoreState
import app.nectarlink.android.core.Device
import app.nectarlink.android.files.transferTitle
+import app.nectarlink.android.calls.PhoneCalls
import app.nectarlink.android.photos.RecentPhotos
import app.nectarlink.android.core.isFinished
import app.nectarlink.core.Transfer
@@ -137,6 +138,17 @@ fun HomeScreen(
) { context.startActivity(NotificationListener.settingsIntent(context)) }
}
}
+ if (state.devices.isNotEmpty() && !state.callAccess) {
+ item {
+ val askCalls = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
+ onAccessChanged()
+ }
+ SetupCard(
+ stringResource(R.string.calls_title),
+ stringResource(R.string.calls_off),
+ ) { askCalls.launch(PhoneCalls.permissions) }
+ }
+ }
if (state.devices.isNotEmpty() && !state.photoAccess) {
item {
val askPhotos = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index d3d52d5..a77ac17 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -67,6 +67,8 @@
<string name="media_previous">Previous</string>
<string name="action_send_files">Send files</string>
<string name="action_send_folder">Send a folder</string>
+ <string name="calls_title">Show calls on your PC</string>
+ <string name="calls_off">See who’s calling on your PC, and answer or decline from there. The call itself stays on your phone. Nectarlink needs access to calls and contacts for that.</string>
<string name="photos_title">Show new photos on your PC</string>
<string name="photos_off">Screenshots and photos you take pop up on your PC, ready to save or paste. Nectarlink needs access to your photos for that.</string>
<string name="transfer_too_many">That folder has too many files to send at once.</string>
diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rs
index e3a5e31..3a1901c 100644
--- a/core/nectarlink-cli/src/main.rs
+++ b/core/nectarlink-cli/src/main.rs
@@ -164,6 +164,12 @@ enum Command {
/// Show new photos from paired phones as this PC would, and fetch each
/// one; stays online until Ctrl+C.
Photos,
+ /// Show calls on paired phones as this PC would; with --auto, answer,
+ /// decline or silence each ringing call. Stays online until Ctrl+C.
+ Calls {
+ #[arg(long, value_enum)]
+ auto: Option<CallArg>,
+ },
/// Announce a picture as a photo just taken on this phone (use with
/// --as-phone), then stay online to send it to PCs that ask.
Photo {
@@ -244,6 +250,13 @@ impl From<MediaCommandArg> for MediaAction {
static MEDIA_COMMANDS: std::sync::OnceLock<tokio::sync::mpsc::UnboundedSender<(MediaAction, Option<u64>)>> =
std::sync::OnceLock::new();
+#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
+enum CallArg {
+ Answer,
+ Decline,
+ Silence,
+}
+
#[derive(Debug, Clone, Copy, ValueEnum)]
enum OnOff {
On,
@@ -513,6 +526,34 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
node.update_power(node_power(cli), offers).await;
watch(node, true).await?;
}
+ Command::Calls { auto } => {
+ let mut offers = cli.offers.clone();
+ offers.push(nectarlink_core::CALLS_SHOW.into());
+ node.update_power(node_power(cli), offers).await;
+ let command = auto.map(|a| match a {
+ CallArg::Answer => nectarlink_core::CallCommand::Answer,
+ CallArg::Decline => nectarlink_core::CallCommand::Decline,
+ CallArg::Silence => nectarlink_core::CallCommand::Silence,
+ });
+ let mut events = node.events();
+ let answerer = node.clone();
+ tokio::spawn(async move {
+ while let Ok(event) = events.recv().await {
+ if let (Some(command), NodeEvent::Call { device, call }) = (command, &event)
+ && call.state == "ringing"
+ && call.incoming
+ {
+ // Long enough to see it ring.
+ tokio::time::sleep(std::time::Duration::from_secs(3)).await;
+ match answerer.call_command(*device, call.id.clone(), command).await {
+ Ok(()) => println!("Did it: {command:?}."),
+ Err(e) => println!("Couldn't {command:?}: {e}"),
+ }
+ }
+ }
+ });
+ watch(node, false).await?;
+ }
Command::Power { device, action } => {
let id = resolve(node, device)?;
wait_until_online(node, id).await?;
@@ -859,6 +900,25 @@ fn print_event(node: &Node, event: &NodeEvent) {
println!("{}: a notification went away", name(device))
}
NodeEvent::ClipboardReceived { device } => println!("{}: sent its clipboard", name(device)),
+ NodeEvent::Call { device, call } => println!(
+ "{}: {} call {} {}{}{}",
+ name(device),
+ if call.incoming { "incoming" } else { "outgoing" },
+ call.id,
+ call.state,
+ match (&call.name, &call.number) {
+ (Some(n), Some(num)) => format!(" from {n} ({num})"),
+ (None, Some(num)) => format!(" from {num}"),
+ _ => String::new(),
+ },
+ if call.missed {
+ ", missed"
+ } else if call.photo.is_some() {
+ ", with photo"
+ } else {
+ ""
+ },
+ ),
NodeEvent::PhotoAdded { device, photo } => println!(
"{}: new {} {} ({} bytes, preview {} bytes)",
name(device),
diff --git a/core/nectarlink-core/src/calls.rs b/core/nectarlink-core/src/calls.rs
new file mode 100644
index 0000000..5896ede
--- /dev/null
+++ b/core/nectarlink-core/src/calls.rs
@@ -0,0 +1,189 @@
+// SPDX-License-Identifier: MPL-2.0
+//! Calls (docs/protocol/calls.md): a phone tells its PCs when a call rings,
+//! is answered and ends; a PC can answer, decline or silence it. The call's
+//! audio stays on the phone.
+
+use std::sync::{Arc, Mutex};
+
+use nectarlink_protocol::{
+ Envelope, ErrorCode,
+ messages::{CallAction, CallState, calls, types},
+};
+
+use crate::{Error, Result, events::NodeEvent, node::Shared, session::Session};
+
+/// The device toggle that allows calls for a device.
+pub(crate) const TOGGLE: &str = "calls";
+
+/// What a PC can ask a phone to do with a call.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CallCommand {
+ Answer,
+ /// Declines a ringing call, or hangs up an active one.
+ Decline,
+ /// Stops the ringing; the call still rings on for the caller.
+ Silence,
+}
+
+impl CallCommand {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ CallCommand::Answer => calls::ANSWER,
+ CallCommand::Decline => calls::DECLINE,
+ CallCommand::Silence => calls::SILENCE,
+ }
+ }
+
+ pub fn parse(action: &str) -> Option<CallCommand> {
+ match action {
+ calls::ANSWER => Some(CallCommand::Answer),
+ calls::DECLINE => Some(CallCommand::Decline),
+ calls::SILENCE => Some(CallCommand::Silence),
+ _ => None,
+ }
+ }
+}
+
+/// The phone's call in progress (ringing or active), for PCs that connect
+/// while it's going on.
+#[derive(Debug, Default)]
+pub(crate) struct Current(Mutex<Option<CallState>>);
+
+impl Current {
+ fn get(&self) -> Option<CallState> {
+ self.0.lock().unwrap_or_else(|e| e.into_inner()).clone()
+ }
+
+ fn set(&self, call: &CallState) {
+ *self.0.lock().unwrap_or_else(|e| e.into_inner()) =
+ (call.state != calls::ENDED).then(|| call.clone());
+ }
+}
+
+impl Shared {
+ /// Whether this PC takes calls from `session`'s phone.
+ fn call_target(&self, session: &Session) -> bool {
+ self.is_desktop(&session.peer)
+ && self.toggle_on(&session.peer, TOGGLE)
+ && self.store.get_peer(&session.peer).ok().flatten().is_some_and(|p| p.caps.contains(calls::SHOW))
+ }
+
+ pub(crate) async fn call_changed(&self, call: CallState) -> Result<()> {
+ if !call.is_valid() {
+ return Err(if call.photo.as_ref().is_some_and(|p| p.len() > calls::MAX_PHOTO_BYTES) {
+ Error::TooLarge
+ } else {
+ Error::Protocol("invalid call".into())
+ });
+ }
+ self.calls.set(&call);
+ let env = Envelope::new(types::CALL_STATE, &call)?;
+ for session in self.live_sessions().into_iter().filter(|s| self.call_target(s)) {
+ let _ = session.send(env.clone()).await;
+ }
+ Ok(())
+ }
+
+ /// Tells a PC that just connected about the call going on, if any.
+ pub(crate) async fn send_call_state(&self, session: &Arc<Session>) {
+ let Some(call) = self.calls.get() else { return };
+ if self.call_target(session)
+ && let Ok(env) = Envelope::new(types::CALL_STATE, &call)
+ {
+ let _ = session.send(env).await;
+ }
+ }
+}
+
+pub(crate) async fn command(
+ shared: &Shared,
+ session: &Session,
+ id: String,
+ command: CallCommand,
+) -> Result<()> {
+ if !shared.toggle_on(&session.peer, TOGGLE) {
+ return Err(Error::Denied);
+ }
+ let env = Envelope::new(types::CALL_ACTION, &CallAction { id, action: command.as_str().into() })?;
+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect(types::OK)?;
+ Ok(())
+}
+
+/// Handles `call.*`. Returns false for other types.
+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::CALL_STATE => {
+ let call: CallState = env.body()?;
+ let shows = shared.local_capabilities().iter().any(|c| c == calls::SHOW);
+ if shows && call.is_valid() && shared.toggle_on(&peer, TOGGLE) {
+ shared.emit(NodeEvent::Call { device: peer, call });
+ }
+ Ok(true)
+ }
+ types::CALL_ACTION => {
+ let CallAction { id, action } = env.body()?;
+ let current = shared.calls.get();
+ let reply = if !shared.toggle_on(&peer, TOGGLE) {
+ Envelope::error(ErrorCode::Denied, "calls are off for this device")
+ } else if !shared.local_capabilities().iter().any(|c| c == calls::CONTROL) {
+ Envelope::error(ErrorCode::Unsupported, "this phone doesn't take call actions")
+ } else {
+ match (CallCommand::parse(&action), current) {
+ (None, _) => Envelope::error(ErrorCode::Unsupported, "unknown action"),
+ (Some(command), Some(call))
+ if call.id == id
+ && (call.state == calls::RINGING || command == CallCommand::Decline) =>
+ {
+ let platform = shared.platform.clone();
+ match tokio::task::spawn_blocking(move || platform.call_command(&id, command))
+ .await
+ .unwrap_or_else(|e| Err(e.to_string()))
+ {
+ Ok(()) => Envelope::empty(types::OK),
+ Err(reason) => {
+ tracing::warn!(reason, action = command.as_str(), "a call action failed");
+ Envelope::error(ErrorCode::Internal, "the phone couldn't do it")
+ }
+ }
+ }
+ _ => Envelope::error(ErrorCode::NotFound, "no such call"),
+ }
+ };
+ session.send(reply.reply_to(env.id)).await?;
+ Ok(true)
+ }
+ _ => Ok(false),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn commands_round_trip() {
+ for c in [CallCommand::Answer, CallCommand::Decline, CallCommand::Silence] {
+ assert_eq!(CallCommand::parse(c.as_str()), Some(c));
+ }
+ assert_eq!(CallCommand::parse("hold"), None);
+ }
+
+ #[test]
+ fn only_calls_in_progress_are_kept() {
+ let current = Current::default();
+ let call = CallState {
+ id: "7".into(),
+ state: calls::RINGING.into(),
+ incoming: true,
+ number: None,
+ name: None,
+ photo: None,
+ missed: false,
+ };
+ current.set(&call);
+ assert_eq!(current.get().map(|c| c.id), Some("7".into()));
+ current.set(&CallState { state: calls::ENDED.into(), ..call });
+ assert!(current.get().is_none());
+ }
+}
diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rs
index d572ea1..9cbefd1 100644
--- a/core/nectarlink-core/src/config.rs
+++ b/core/nectarlink-core/src/config.rs
@@ -123,6 +123,12 @@ pub trait Platform: Send + Sync + 'static {
Err("this device doesn't share photos".into())
}
+ /// Answer, decline or silence this phone's call `id` (a PC asked; the
+ /// core checked it's the call in progress). `Err` holds a reason for logs.
+ fn call_command(&self, _id: &str, _command: crate::CallCommand) -> Result<(), String> {
+ Err("this device doesn't take calls".into())
+ }
+
/// Run a command on one of this device's media players (a paired device
/// asked); `position` is set for [`MediaAction::Seek`].
fn media_command(
diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rs
index 1e908b0..0425b7d 100644
--- a/core/nectarlink-core/src/events.rs
+++ b/core/nectarlink-core/src/events.rs
@@ -134,4 +134,9 @@ pub enum NodeEvent {
device: DeviceId,
photo: crate::Photo,
},
+ /// A call on a phone rang, was answered or ended.
+ Call {
+ device: DeviceId,
+ call: crate::CallState,
+ },
}
diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rs
index 17f0e46..8f3964f 100644
--- a/core/nectarlink-core/src/features.rs
+++ b/core/nectarlink-core/src/features.rs
@@ -600,6 +600,16 @@ pub const FEATURES: &[FeatureDef] = &[
requires: &[phone("call.state", Unlock::Permission(Permission::Phone)), DeviceToggle("calls")],
partial: None,
},
+ FeatureDef {
+ id: "calls.control",
+ group: FeatureGroup::Calls,
+ requires: &[
+ phone("call.state", Unlock::Permission(Permission::Phone)),
+ phone("call.control", Unlock::Permission(Permission::Phone)),
+ DeviceToggle("calls"),
+ ],
+ partial: None,
+ },
// Clipboard
FeatureDef {
id: "clipboard.pc_to_phone",
diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rs
index 4f1ede1..71382a0 100644
--- a/core/nectarlink-core/src/lib.rs
+++ b/core/nectarlink-core/src/lib.rs
@@ -7,6 +7,7 @@
//! `docs/architecture/core-api.md` for the design.
mod actions;
+mod calls;
mod clipboard;
mod config;
mod error;
@@ -23,6 +24,7 @@ mod store;
mod transfer;
pub use actions::PowerAction;
+pub use calls::CallCommand;
pub use config::{NodeConfig, NoopPlatform, Platform};
pub use error::{Error, Result, Side};
pub use events::{
@@ -37,8 +39,9 @@ pub use nectarlink_protocol::messages::clip::{
pub use nectarlink_protocol::{
DeviceId,
messages::{
- Battery, CLIP_MAX_BYTES, DeviceInfo, DeviceKind, MediaPlayer, Notification, NotificationAction,
- PhotoNew as Photo, PowerLevel,
+ Battery, CLIP_MAX_BYTES, CallState, DeviceInfo, DeviceKind, MediaPlayer, Notification,
+ NotificationAction, PhotoNew as Photo, PowerLevel,
+ calls::{CONTROL as CALLS_CONTROL, SHOW as CALLS_SHOW, STATE as CALLS_STATE},
photos::{MAX_THUMB_BYTES as PHOTO_MAX_THUMB_BYTES, READ as PHOTOS_READ, SHOW as PHOTOS_SHOW},
},
pairing::PairingUri,
diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rs
index 99c54aa..a96497a 100644
--- a/core/nectarlink-core/src/node.rs
+++ b/core/nectarlink-core/src/node.rs
@@ -117,6 +117,8 @@ pub(crate) struct Shared {
pub players: crate::media::Players,
/// Photos this phone announced lately (docs/protocol/photos.md).
pub(crate) photos: crate::photos::Recent,
+ /// This phone's call in progress (docs/protocol/calls.md).
+ pub(crate) calls: crate::calls::Current,
pub data_dir: std::path::PathBuf,
/// Where received files go.
pub downloads_dir: std::path::PathBuf,
@@ -352,6 +354,7 @@ impl Shared {
}
shared.send_notification_snapshot(&s).await;
shared.send_media_state(&s).await;
+ shared.send_call_state(&s).await;
});
Some(session)
}
@@ -606,6 +609,7 @@ impl Node {
notifications: Feed::default(),
players: Default::default(),
photos: Default::default(),
+ calls: Default::default(),
data_dir: config.data_dir.clone(),
downloads_dir: config.downloads_dir.clone().unwrap_or_else(|| config.data_dir.join("received")),
transfers: Mutex::new(HashMap::new()),
@@ -917,6 +921,20 @@ impl Node {
crate::actions::open_link(&self.shared, &session, url).await
}
+ // ---- Calls (docs/protocol/calls.md) ----
+
+ /// A call on this phone rang, was answered or ended; sent to every
+ /// connected PC the user allows (and to PCs that connect during it).
+ pub async fn call_changed(&self, call: crate::CallState) -> Result<()> {
+ self.shared.call_changed(call).await
+ }
+
+ /// Answers, declines or silences a call on a paired phone.
+ pub async fn call_command(&self, peer: DeviceId, id: String, command: crate::CallCommand) -> Result<()> {
+ let session = self.connected(&peer)?;
+ crate::calls::command(&self.shared, &session, id, command).await
+ }
+
// ---- Photos (docs/protocol/photos.md) ----
/// A photo or screenshot just appeared on this phone; announced to every
diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rs
index 4e6993d..65a6062 100644
--- a/core/nectarlink-core/src/session.rs
+++ b/core/nectarlink-core/src/session.rs
@@ -351,6 +351,7 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->
&& crate::actions::handle(shared, session, &env).await? => {}
t if t.starts_with("clip.") && crate::clipboard::handle(shared, session, &env).await? => {}
t if t.starts_with("photos.") && crate::photos::handle(shared, session, &env).await? => {}
+ t if t.starts_with("call.") && crate::calls::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/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index 19b4fd8..ba0ae75 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -30,6 +30,7 @@ struct RecordingPlatform {
media: Mutex<Vec<(String, MediaAction, Option<u64>)>>,
power: Mutex<Vec<PowerAction>>,
links: Mutex<Vec<String>>,
+ calls: Mutex<Vec<(String, nectarlink_core::CallCommand)>>,
/// Photos `open_photo` finds, by ID.
photos: Mutex<std::collections::HashMap<String, std::path::PathBuf>>,
}
@@ -73,6 +74,10 @@ impl Platform for RecordingPlatform {
self.links.lock().unwrap().push(url.to_owned());
Ok(())
}
+ fn call_command(&self, id: &str, command: nectarlink_core::CallCommand) -> Result<(), String> {
+ self.calls.lock().unwrap().push((id.to_owned(), command));
+ Ok(())
+ }
fn open_photo(&self, id: &str) -> Result<OutgoingFile, String> {
let path = self.photos.lock().unwrap().get(id).cloned().ok_or("gone")?;
let name = path.file_name().unwrap().to_string_lossy().into_owned();
@@ -943,6 +948,72 @@ async fn folders_arrive_with_their_layout() {
);
}
+#[tokio::test(flavor = "multi_thread")]
+async fn calls_show_on_the_pc_which_can_answer_them() {
+ use nectarlink_core::{CallCommand, CallState};
+ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[nectarlink_core::CALLS_SHOW]).await;
+ let mut phone = device_with(
+ "Pixel",
+ DeviceKind::Phone,
+ &[nectarlink_core::CALLS_STATE, nectarlink_core::CALLS_CONTROL],
+ )
+ .await;
+ pair_qr(&mut pc, &mut phone).await;
+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());
+ let ringing = CallState {
+ id: "c1".into(),
+ state: "ringing".into(),
+ incoming: true,
+ number: Some("+15550100".into()),
+ name: Some("Sam".into()),
+ photo: Some(vec![0xff, 0xd8]),
+ missed: false,
+ };
+ async fn next_call(pc: &mut TestDevice, phone_id: nectarlink_core::DeviceId) -> CallState {
+ wait_for(pc, "a call", |e| match e {
+ NodeEvent::Call { device, call } if *device == phone_id => Some(call.clone()),
+ _ => None,
+ })
+ .await
+ }
+
+ phone.node.call_changed(ringing.clone()).await.unwrap();
+ assert_eq!(next_call(&mut pc, phone_id).await, ringing);
+ with_timeout("answer", pc.node.call_command(phone_id, "c1".into(), CallCommand::Answer)).await.unwrap();
+ assert_eq!(*phone.platform.calls.lock().unwrap(), [("c1".to_owned(), CallCommand::Answer)]);
+ // Only the call in progress.
+ assert!(matches!(
+ pc.node.call_command(phone_id, "c0".into(), CallCommand::Decline).await,
+ Err(Error::NotFound)
+ ));
+
+ let active = CallState { state: "active".into(), photo: None, ..ringing.clone() };
+ phone.node.call_changed(active.clone()).await.unwrap();
+ assert_eq!(next_call(&mut pc, phone_id).await.state, "active");
+ // An answered call doesn't ring anymore, but can be hung up.
+ assert!(matches!(
+ pc.node.call_command(phone_id, "c1".into(), CallCommand::Silence).await,
+ Err(Error::NotFound)
+ ));
+ pc.node.call_command(phone_id, "c1".into(), CallCommand::Decline).await.unwrap();
+
+ let ended = CallState { state: "ended".into(), ..active };
+ phone.node.call_changed(ended).await.unwrap();
+ assert_eq!(next_call(&mut pc, phone_id).await.state, "ended");
+ assert!(matches!(
+ pc.node.call_command(phone_id, "c1".into(), CallCommand::Decline).await,
+ Err(Error::NotFound)
+ ));
+
+ // The phone's user turned calls off for this PC.
+ phone.node.set_device_toggle(pc_id, "calls", false).unwrap();
+ phone.node.call_changed(CallState { id: "c2".into(), ..ringing }).await.unwrap();
+ assert!(matches!(
+ pc.node.call_command(phone_id, "c2".into(), CallCommand::Answer).await,
+ Err(Error::Denied)
+ ));
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn new_photos_reach_the_pc_and_come_when_asked() {
let mut pc = device_with("Desktop", DeviceKind::Desktop, &[nectarlink_core::PHOTOS_SHOW]).await;
diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rs
index ea2ed9a..808be9c 100644
--- a/core/nectarlink-ffi/src/lib.rs
+++ b/core/nectarlink-ffi/src/lib.rs
@@ -429,6 +429,51 @@ pub enum Event {
id: String,
photo_id: String,
},
+ /// A call on a paired phone changed (PCs only; phones report theirs).
+ CallChanged {
+ id: String,
+ call_id: String,
+ },
+}
+
+/// A call on this phone (docs/protocol/calls.md).
+#[derive(Clone, PartialEq, Eq, uniffi::Record)]
+pub struct Call {
+ /// This app's ID for the call, the same while it lasts.
+ pub id: String,
+ pub state: CallPhase,
+ pub incoming: bool,
+ pub number: Option<String>,
+ /// The contact's name, when the number is a contact.
+ pub name: Option<String>,
+ /// The contact's photo: a JPEG of at most 64 KB, sent while ringing.
+ pub photo: Option<Vec<u8>>,
+ /// With `Ended`: it rang and nobody answered.
+ pub missed: bool,
+}
+
+/// Never prints the number, name or photo (protocol v0 §11).
+impl std::fmt::Debug for Call {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Call").field("id", &self.id).field("state", &self.state).finish_non_exhaustive()
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
+pub enum CallPhase {
+ Ringing,
+ Active,
+ Ended,
+}
+
+/// What a PC asked of a call.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
+pub enum CallCommand {
+ Answer,
+ /// Decline a ringing call, or hang up an active one.
+ Decline,
+ /// Stop the ringing.
+ Silence,
}
/// A photo or screenshot that just appeared on this phone
@@ -820,6 +865,9 @@ impl From<NodeEvent> for Event {
NodeEvent::PhotoAdded { device, photo } => {
Event::PhotoAdded { id: device.to_string(), photo_id: photo.id }
}
+ NodeEvent::Call { device, call } => {
+ Event::CallChanged { id: device.to_string(), call_id: call.id }
+ }
}
}
}
@@ -926,6 +974,9 @@ pub trait Platform: Send + Sync {
/// A PC asked for a photo announced with `photo_taken`: open it, or
/// `null` when it's gone.
fn open_photo(&self, id: String) -> Option<FileToSend>;
+ /// A PC asked to answer, decline or silence call `id` (the call in
+ /// progress). False if the phone couldn't.
+ fn call_command(&self, id: String, command: CallCommand) -> bool;
}
/// Encrypts the device key at rest (Android: a Keystore key).
@@ -988,6 +1039,14 @@ impl core::Platform for PlatformAdapter {
Err("the clipboard rejected it".into())
}
}
+ fn call_command(&self, id: &str, command: core::CallCommand) -> Result<(), String> {
+ let command = match command {
+ core::CallCommand::Answer => CallCommand::Answer,
+ core::CallCommand::Decline => CallCommand::Decline,
+ core::CallCommand::Silence => CallCommand::Silence,
+ };
+ if self.0.call_command(id.to_owned(), command) { Ok(()) } else { Err("the phone couldn't".into()) }
+ }
fn open_photo(&self, id: &str) -> Result<core::OutgoingFile, String> {
let file = self.0.open_photo(id.to_owned()).ok_or("it's gone")?;
file_to_send(file).map_err(|e| e.to_string())
@@ -1287,6 +1346,27 @@ impl NectarlinkNode {
self.run(async move { Ok(node.open_link(id, url).await?) }).await
}
+ /// A call on this phone rang, was answered or ended: tells the PCs that
+ /// show calls (and are allowed them), now and when they connect during it.
+ pub async fn call_changed(&self, call: Call) -> Result<()> {
+ let node = self.node.clone();
+ let call = core::CallState {
+ id: call.id,
+ state: match call.state {
+ CallPhase::Ringing => "ringing",
+ CallPhase::Active => "active",
+ CallPhase::Ended => "ended",
+ }
+ .into(),
+ incoming: call.incoming,
+ number: call.number,
+ name: call.name,
+ photo: call.photo,
+ missed: call.missed,
+ };
+ self.run(async move { Ok(node.call_changed(call).await?) }).await
+ }
+
/// A photo or screenshot just appeared on this phone: tells the PCs
/// that show photos (and are allowed them).
pub async fn photo_taken(&self, photo: Photo) -> Result<()> {
diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rs
index 134d946..5101d44 100644
--- a/core/nectarlink-protocol/src/messages.rs
+++ b/core/nectarlink-protocol/src/messages.rs
@@ -43,6 +43,8 @@ pub mod types {
pub const PHOTOS_NEW: &str = "photos.new";
pub const PHOTOS_GET: &str = "photos.get";
pub const PHOTOS_SENDING: &str = "photos.sending";
+ pub const CALL_STATE: &str = "call.state";
+ pub const CALL_ACTION: &str = "call.action";
}
/// What kind of device this is.
@@ -456,6 +458,88 @@ pub struct PcPower {
/// The longest link sent, in bytes.
pub const LINK_MAX_BYTES: usize = 4096;
+// ---- Calls (docs/protocol/calls.md) ----
+
+pub mod calls {
+ /// Offered by phones that report their calls.
+ pub const STATE: &str = "call.state";
+ /// Offered by phones that answer and decline calls when a PC asks.
+ pub const CONTROL: &str = "call.control";
+ /// Offered by PCs that show calls.
+ pub const SHOW: &str = "call.show";
+ /// A caller's photo: a JPEG of at most this many bytes.
+ pub const MAX_PHOTO_BYTES: usize = 64 * 1024;
+ pub const MAX_ID_BYTES: usize = 64;
+ pub const MAX_TEXT_BYTES: usize = 256;
+
+ pub const RINGING: &str = "ringing";
+ pub const ACTIVE: &str = "active";
+ pub const ENDED: &str = "ended";
+
+ pub const ANSWER: &str = "answer";
+ pub const DECLINE: &str = "decline";
+ pub const SILENCE: &str = "silence";
+}
+
+/// Body of `call.state`: a call on the phone started ringing, was
+/// answered, or ended.
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CallState {
+ /// The phone's ID for this call, the same in each of its messages.
+ pub id: String,
+ /// `ringing`, `active` or `ended`.
+ pub state: String,
+ /// Incoming (false: the phone's user made the call).
+ #[serde(default = "yes")]
+ pub incoming: bool,
+ /// The caller's number, when the phone knows it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub number: Option<String>,
+ /// The contact's name, when the number is a contact.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ /// The contact's photo (JPEG), with `ringing` only.
+ #[serde(default, skip_serializing_if = "Option::is_none", with = "serde_bytes")]
+ pub photo: Option<Vec<u8>>,
+ /// With `ended`: it rang and nobody answered.
+ #[serde(default)]
+ pub missed: bool,
+}
+
+fn yes() -> bool {
+ true
+}
+
+/// Never prints the number, name or photo (protocol v0 §11).
+impl std::fmt::Debug for CallState {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("CallState")
+ .field("id", &self.id)
+ .field("state", &self.state)
+ .field("incoming", &self.incoming)
+ .field("missed", &self.missed)
+ .finish_non_exhaustive()
+ }
+}
+
+impl CallState {
+ pub fn is_valid(&self) -> bool {
+ let text_ok = |t: &Option<String>| t.as_ref().is_none_or(|t| t.len() <= calls::MAX_TEXT_BYTES);
+ (1..=calls::MAX_ID_BYTES).contains(&self.id.len())
+ && [calls::RINGING, calls::ACTIVE, calls::ENDED].contains(&self.state.as_str())
+ && text_ok(&self.number)
+ && text_ok(&self.name)
+ && self.photo.as_ref().is_none_or(|p| p.len() <= calls::MAX_PHOTO_BYTES)
+ }
+}
+
+/// Body of `call.action`: answer, decline or silence a ringing call.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CallAction {
+ pub id: String,
+ pub action: String,
+}
+
// ---- Photos (docs/protocol/photos.md) ----
pub mod photos {
@@ -844,6 +928,29 @@ mod tests {
assert!(!format!("{:?}", offer("Secret")).contains("Secret"));
}
+ #[test]
+ fn calls_are_validated() {
+ let call = CallState {
+ id: "1".into(),
+ state: calls::RINGING.into(),
+ incoming: true,
+ number: Some("+1 555 0100".into()),
+ name: Some("Sam".into()),
+ photo: Some(vec![0xff, 0xd8]),
+ missed: false,
+ };
+ assert!(call.is_valid());
+ let shown = format!("{call:?}");
+ assert!(!shown.contains("555") && !shown.contains("Sam"), "{shown}");
+ assert!(!CallState { state: "on hold".into(), ..call.clone() }.is_valid());
+ assert!(!CallState { id: String::new(), ..call.clone() }.is_valid());
+ assert!(!CallState { photo: Some(vec![0; calls::MAX_PHOTO_BYTES + 1]), ..call.clone() }.is_valid());
+ // Missing fields take their defaults: incoming, not missed.
+ let env = Envelope::new("x", &CallState { number: None, name: None, photo: None, ..call }).unwrap();
+ let back: CallState = env.body().unwrap();
+ assert!(back.incoming && !back.missed && back.number.is_none());
+ }
+
#[test]
fn photos_are_validated() {
let photo = PhotoNew {
diff --git a/desktop/app/src/battery.rs b/desktop/app/src/battery.rs
index 5ef4e63..0cfa7b6 100644
--- a/desktop/app/src/battery.rs
+++ b/desktop/app/src/battery.rs
@@ -99,6 +99,7 @@ pub fn on_event(event: &NodeEvent) {
reply: None,
silent: false,
progress: None,
+ call: false,
});
}
diff --git a/desktop/app/src/calls.rs b/desktop/app/src/calls.rs
new file mode 100644
index 0000000..bb0b26f
--- /dev/null
+++ b/desktop/app/src/calls.rs
@@ -0,0 +1,196 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Calls on a phone (docs/protocol/calls.md): a ringing Windows
+//! notification to answer, decline or silence the call (its audio stays on
+//! the phone), and a notification for calls nobody answered.
+
+use std::{collections::HashMap, path::PathBuf, sync::Mutex};
+
+use nectarlink_core::{CallCommand, CallState, DeviceId, Error, FeatureState, LinkState, NodeEvent};
+
+use crate::{
+ bridge::app::{describe, show_message},
+ core_host,
+ win::toast::{self, CALL_ANSWER, CALL_DECLINE, Toast},
+};
+
+/// The toast "device" for calls; their key is `<device ID> <call ID>`.
+pub const TOAST_GROUP: &str = "calls";
+const ACTION_SILENCE: &str = "silence";
+
+/// The ringing call shown per phone, to show it again (silenced) or take it
+/// away when it stops ringing.
+static RINGING: Mutex<Option<HashMap<DeviceId, CallState>>> = Mutex::new(None);
+
+fn ringing<T>(f: impl FnOnce(&mut HashMap<DeviceId, CallState>) -> T) -> T {
+ f(RINGING.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())
+}
+
+fn key(device: DeviceId, call: &str) -> String {
+ format!("{device} {call}")
+}
+
+pub fn on_event(event: &NodeEvent) {
+ match event {
+ NodeEvent::Call { device, call } => changed(*device, call),
+ // A phone that's gone can't be answered from here.
+ NodeEvent::LinkChanged { device, link: LinkState::Offline { .. } } => stop_ringing(*device),
+ _ => {}
+ }
+}
+
+fn changed(device: DeviceId, call: &CallState) {
+ match call.state.as_str() {
+ "ringing" if call.incoming => {
+ if let Some(previous) = ringing(|r| r.insert(device, call.clone()))
+ && previous.id != call.id
+ {
+ toast::remove(TOAST_GROUP, &key(device, &previous.id));
+ }
+ show_ringing(device, call, false);
+ }
+ "ended" if call.missed => {
+ stop_ringing(device);
+ show_missed(device, call);
+ }
+ // Answered (here or on the phone) or over.
+ _ => stop_ringing(device),
+ }
+}
+
+fn stop_ringing(device: DeviceId) {
+ if let Some(call) = ringing(|r| r.remove(&device)) {
+ toast::remove(TOAST_GROUP, &key(device, &call.id));
+ }
+}
+
+/// Who's calling, as well as the phone knows.
+fn caller(call: &CallState) -> String {
+ call.name
+ .clone()
+ .filter(|n| !n.trim().is_empty())
+ .or_else(|| call.number.clone().filter(|n| !n.trim().is_empty()))
+ .unwrap_or_else(|| "Unknown caller".into())
+}
+
+fn phone_name(device: DeviceId) -> String {
+ core_host::host().hub.read(|s| s.name_of(&device)).unwrap_or_else(|| "your phone".into())
+}
+
+fn show_ringing(device: DeviceId, call: &CallState, silenced: bool) {
+ let controls = core_host::host().hub.read(|s| {
+ s.matrices.get(&device).and_then(|m| m.state("calls.control")) == Some(FeatureState::Available)
+ });
+ let mut actions = Vec::new();
+ if controls {
+ actions.push((CALL_ANSWER.to_owned(), "Answer".to_owned()));
+ actions.push((CALL_DECLINE.to_owned(), "Decline".to_owned()));
+ if !silenced {
+ actions.push((ACTION_SILENCE.to_owned(), "Silence".to_owned()));
+ }
+ }
+ // The number under the name, when there's a name.
+ let body = match (&call.name, &call.number) {
+ (Some(name), Some(number)) if !name.trim().is_empty() => {
+ format!("{number} · on {}", phone_name(device))
+ }
+ _ => format!("Calling {}", phone_name(device)),
+ };
+ toast::show(Toast {
+ device: TOAST_GROUP.into(),
+ key: key(device, &call.id),
+ title: caller(call),
+ body,
+ attribution: "Nectarlink".into(),
+ icon: call.photo.as_deref().and_then(|photo| save_photo(device, &call.id, photo)),
+ image: None,
+ actions,
+ reply: None,
+ silent: silenced,
+ progress: None,
+ call: true,
+ });
+}
+
+fn show_missed(device: DeviceId, call: &CallState) {
+ toast::show(Toast {
+ device: TOAST_GROUP.into(),
+ key: format!("missed {}", key(device, &call.id)),
+ title: format!("Missed call from {}", caller(call)),
+ body: format!("On {}", phone_name(device)),
+ attribution: "Nectarlink".into(),
+ icon: None,
+ image: None,
+ actions: Vec::new(),
+ reply: None,
+ silent: false,
+ progress: None,
+ call: false,
+ });
+}
+
+/// The caller's photo as a file, for the notification.
+fn save_photo(device: DeviceId, call: &str, photo: &[u8]) -> Option<PathBuf> {
+ let dir = crate::notifications::images_dir();
+ let path = dir.join(format!("call-{:016x}.jpg", crate::photos::fingerprint(&key(device, call))));
+ match std::fs::create_dir_all(&dir).and_then(|()| std::fs::write(&path, photo)) {
+ Ok(()) => Some(path),
+ Err(e) => {
+ tracing::warn!(error = %e, "can't keep a caller's photo");
+ None
+ }
+ }
+}
+
+/// The user pressed a button on a call notification.
+pub fn on_toast(key: &str, action: &str) {
+ if key.starts_with("missed ") {
+ return;
+ }
+ let Some((device, call)) = key.split_once(' ') else { return };
+ let Ok(device) = device.parse::<DeviceId>() else { return };
+ let command = match action {
+ CALL_ANSWER => CallCommand::Answer,
+ CALL_DECLINE => CallCommand::Decline,
+ ACTION_SILENCE => CallCommand::Silence,
+ _ => return,
+ };
+ let Some(node) = core_host::node() else { return };
+ let call = call.to_owned();
+ core_host::spawn(async move {
+ match node.call_command(device, call.clone(), command).await {
+ // Quiet now, but still ringing for the caller: the buttons stay.
+ Ok(()) if command == CallCommand::Silence => {
+ if let Some(ringing) = ringing(|r| r.get(&device).filter(|c| c.id == call).cloned()) {
+ show_ringing(device, &ringing, true);
+ }
+ }
+ Ok(()) => {}
+ Err(Error::NotFound) => show_message("That call is over."),
+ Err(e) => show_message(describe(&e)),
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn call(name: Option<&str>, number: Option<&str>) -> CallState {
+ CallState {
+ id: "1".into(),
+ state: "ringing".into(),
+ incoming: true,
+ number: number.map(Into::into),
+ name: name.map(Into::into),
+ photo: None,
+ missed: false,
+ }
+ }
+
+ #[test]
+ fn callers_are_named_as_well_as_known() {
+ assert_eq!(caller(&call(Some("Sam"), Some("+1555"))), "Sam");
+ assert_eq!(caller(&call(Some(" "), Some("+1555"))), "+1555");
+ assert_eq!(caller(&call(None, None)), "Unknown caller");
+ }
+}
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
index 3b9390a..e7ba838 100644
--- a/desktop/app/src/core_host.rs
+++ b/desktop/app/src/core_host.rs
@@ -95,8 +95,12 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
let mut config = NodeConfig::new(&data_dir, this_device(), env!("CARGO_PKG_VERSION"));
config.downloads_dir = Some(downloads_dir());
// This PC's own players, for phones (crate::win::media_sessions).
- config.capabilities =
- vec!["media.control".into(), "pc.power".into(), nectarlink_core::PHOTOS_SHOW.into()];
+ config.capabilities = vec![
+ "media.control".into(),
+ "pc.power".into(),
+ nectarlink_core::PHOTOS_SHOW.into(),
+ nectarlink_core::CALLS_SHOW.into(),
+ ];
let node = match Node::start(config, platform).await {
Ok(node) => node,
Err(e) => {
@@ -143,6 +147,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
crate::notifications::update_toasts(&event);
crate::clipboard::on_event(&event);
crate::photos::on_event(&event);
+ crate::calls::on_event(&event);
crate::transfers::on_event(&event);
crate::send_to::on_event(&event);
crate::battery::on_event(&event);
diff --git a/desktop/app/src/links.rs b/desktop/app/src/links.rs
index 18ff224..9b1e4ea 100644
--- a/desktop/app/src/links.rs
+++ b/desktop/app/src/links.rs
@@ -54,6 +54,7 @@ fn notice(title: &str, body: &str) {
reply: None,
silent: true,
progress: None,
+ call: false,
});
}
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index bbee16f..dfc1db3 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -10,6 +10,7 @@
mod battery;
mod bridge;
+mod calls;
mod clipboard;
mod core_host;
mod doctor;
diff --git a/desktop/app/src/notifications.rs b/desktop/app/src/notifications.rs
index 76f6861..db53f1b 100644
--- a/desktop/app/src/notifications.rs
+++ b/desktop/app/src/notifications.rs
@@ -181,6 +181,7 @@ fn show(device: DeviceId, n: &Notification) {
reply: reply.map(|a| (a.id.clone(), a.title.clone())),
silent: n.silent,
progress: None,
+ call: false,
};
toasted(|t| t.entry(device).or_default().insert(n.key.clone()));
toast::show(toast);
@@ -218,6 +219,11 @@ pub fn on_toast(event: ToastEvent) {
return crate::photos::on_toast(key, Some(action));
}
ToastEvent::Dismissed { device, .. } if device == crate::photos::TOAST_GROUP => return,
+ // Calls: answer, decline or silence; dismissing only hides it.
+ ToastEvent::Action { device, key, action } if device == crate::calls::TOAST_GROUP => {
+ return crate::calls::on_toast(key, action);
+ }
+ ToastEvent::Dismissed { device, .. } if device == crate::calls::TOAST_GROUP => return,
ToastEvent::Dismissed { device, .. } | ToastEvent::Action { device, .. }
if device == crate::battery::TOAST_GROUP =>
{
diff --git a/desktop/app/src/photos.rs b/desktop/app/src/photos.rs
index d13bcc4..23cd393 100644
--- a/desktop/app/src/photos.rs
+++ b/desktop/app/src/photos.rs
@@ -84,6 +84,7 @@ fn show(device: DeviceId, photo: &Photo) {
reply: None,
silent: true,
progress: None,
+ call: false,
});
}
@@ -104,7 +105,7 @@ fn save_preview(device: DeviceId, photo: &Photo) -> Option<PathBuf> {
}
}
-fn fingerprint(text: &str) -> u64 {
+pub(crate) fn fingerprint(text: &str) -> u64 {
text.bytes().fold(0xcbf2_9ce4_8422_2325, |hash, b| (hash ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3))
}
diff --git a/desktop/app/src/send_to.rs b/desktop/app/src/send_to.rs
index e6cd11c..0891418 100644
--- a/desktop/app/src/send_to.rs
+++ b/desktop/app/src/send_to.rs
@@ -255,6 +255,7 @@ fn failed(title: &str, body: &str) {
reply: None,
silent: false,
progress: None,
+ call: false,
});
}
@@ -296,6 +297,7 @@ fn update(map: &mut HashMap<String, Tracked>, transfer: &Transfer) {
reply: None,
silent: false,
progress: None,
+ call: false,
};
match &transfer.state {
TransferState::Waiting | TransferState::Running => {
diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rs
index 03d749e..1b38d08 100644
--- a/desktop/app/src/state.rs
+++ b/desktop/app/src/state.rs
@@ -380,9 +380,11 @@ impl AppState {
let gone = self.notifications.remove(at);
Changes::NOTIFICATIONS | self.remember(vec![gone])
}
- // Feedback (crate::clipboard) and notifications (crate::photos)
- // only; nothing to keep.
- NodeEvent::ClipboardReceived { .. } | NodeEvent::PhotoAdded { .. } => Changes::NONE,
+ // Feedback (crate::clipboard) and notifications (crate::photos,
+ // crate::calls) only; nothing to keep.
+ NodeEvent::ClipboardReceived { .. } | NodeEvent::PhotoAdded { .. } | NodeEvent::Call { .. } => {
+ Changes::NONE
+ }
NodeEvent::Transfer(transfer) => self.update_transfer(transfer.clone(), Instant::now()),
// With artwork saved first (see crate::media).
NodeEvent::MediaChanged { .. } => Changes::NONE,
diff --git a/desktop/app/src/transfers.rs b/desktop/app/src/transfers.rs
index 7db8e71..85f182f 100644
--- a/desktop/app/src/transfers.rs
+++ b/desktop/app/src/transfers.rs
@@ -92,5 +92,6 @@ pub fn on_event(event: &NodeEvent) {
reply: None,
silent: false,
progress: None,
+ call: false,
});
}
diff --git a/desktop/app/src/updater.rs b/desktop/app/src/updater.rs
index 1e938e1..7f91ff2 100644
--- a/desktop/app/src/updater.rs
+++ b/desktop/app/src/updater.rs
@@ -122,6 +122,7 @@ fn announce(update: &Update) {
reply: None,
silent: true,
progress: None,
+ call: false,
});
}
diff --git a/desktop/app/src/win/toast.rs b/desktop/app/src/win/toast.rs
index 067cb37..0e30580 100644
--- a/desktop/app/src/win/toast.rs
+++ b/desktop/app/src/win/toast.rs
@@ -72,6 +72,9 @@ pub struct Toast {
pub silent: bool,
/// A progress bar, updated in place with [`update_progress`].
pub progress: Option<Progress>,
+ /// An incoming call: stays up and rings until answered or removed, with
+ /// the icon (the caller's photo) in a circle.
+ pub call: bool,
}
/// A toast's progress bar.
@@ -379,9 +382,17 @@ fn escape(text: &str) -> String {
out
}
+/// On a call toast, the actions shown as Answer (green) and Decline (red).
+pub const CALL_ANSWER: &str = "answer";
+pub const CALL_DECLINE: &str = "decline";
+
/// The toast's XML (Windows toast schema).
fn toast_xml(toast: &Toast) -> String {
- let mut xml = String::from(r#"<toast launch="open"><visual><binding template="ToastGeneric">"#);
+ let mut xml = String::from(if toast.call {
+ r#"<toast launch="open" scenario="incomingCall" useButtonStyle="true"><visual><binding template="ToastGeneric">"#
+ } else {
+ r#"<toast launch="open"><visual><binding template="ToastGeneric">"#
+ });
xml.push_str(&format!(r#"<text hint-maxLines="1">{}</text>"#, escape(&toast.title)));
if !toast.body.is_empty() {
xml.push_str(&format!("<text>{}</text>", escape(&toast.body)));
@@ -396,8 +407,9 @@ fn toast_xml(toast: &Toast) -> String {
));
}
if let Some(icon) = &toast.icon {
+ let crop = if toast.call { r#" hint-crop="circle""# } else { "" };
xml.push_str(&format!(
- r#"<image placement="appLogoOverride" src="{}"/>"#,
+ r#"<image placement="appLogoOverride"{crop} src="{}"/>"#,
escape(&crate::icons::file_url(icon))
));
}
@@ -417,12 +429,24 @@ fn toast_xml(toast: &Toast) -> String {
// Windows shows at most five buttons, the send button included.
let room = 5 - usize::from(toast.reply.is_some());
for (id, label) in toast.actions.iter().take(room) {
- xml.push_str(&format!(r#"<action content="{}" arguments="a:{}"/>"#, escape(label), escape(id)));
+ // On a call: Answer green, Decline red.
+ let style = match (toast.call, id.as_str()) {
+ (true, CALL_ANSWER) => r#" hint-buttonStyle="Success""#,
+ (true, CALL_DECLINE) => r#" hint-buttonStyle="Critical""#,
+ _ => "",
+ };
+ xml.push_str(&format!(
+ r#"<action content="{}" arguments="a:{}"{style}/>"#,
+ escape(label),
+ escape(id)
+ ));
}
xml.push_str("</actions>");
}
if toast.silent {
xml.push_str(r#"<audio silent="true"/>"#);
+ } else if toast.call {
+ xml.push_str(r#"<audio src="ms-winsoundevent:Notification.Looping.Call" loop="true"/>"#);
}
xml.push_str("</toast>");
xml
@@ -445,6 +469,7 @@ mod tests {
reply: Some(("r".into(), "Reply".into())),
silent: true,
progress: None,
+ call: false,
}
}
@@ -462,6 +487,21 @@ mod tests {
XmlDocument::new().unwrap().LoadXml(&HSTRING::from(xml)).expect("well-formed XML");
}
+ #[test]
+ fn calls_ring_until_handled() {
+ let actions = vec![(CALL_ANSWER.into(), "Answer".into()), (CALL_DECLINE.into(), "Decline".into())];
+ let xml = toast_xml(&Toast { call: true, silent: false, reply: None, actions, ..toast() });
+ assert!(
+ xml.starts_with(r#"<toast launch="open" scenario="incomingCall" useButtonStyle="true">"#),
+ "{xml}"
+ );
+ assert!(xml.contains(r#"arguments="a:answer" hint-buttonStyle="Success""#), "{xml}");
+ assert!(xml.contains(r#"arguments="a:decline" hint-buttonStyle="Critical""#), "{xml}");
+ assert!(xml.contains(r#"placement="appLogoOverride" hint-crop="circle""#), "{xml}");
+ assert!(xml.contains(r#"Notification.Looping.Call" loop="true""#), "{xml}");
+ XmlDocument::new().unwrap().LoadXml(&HSTRING::from(xml)).expect("well-formed XML");
+ }
+
#[test]
fn progress_bars_are_bound_to_data() {
let toast = Toast {
diff --git a/docs/protocol/calls.md b/docs/protocol/calls.md
new file mode 100644
index 0000000..6dd1e06
--- /dev/null
+++ b/docs/protocol/calls.md
@@ -0,0 +1,61 @@
+# Calls service (protocol v0)
+
+> Status: **draft.** Builds on [protocol v0](v0.md); breaking changes are
+> allowed until v1. License: CC BY 4.0.
+
+A phone tells its PCs about its calls: who's calling, when it's answered,
+and when it ends. A PC can answer, decline or silence a ringing call. The
+call's audio stays on the phone; this service carries no sound.
+
+## 1. Capabilities
+
+| ID | Offered by | Meaning |
+|---|---|---|
+| `call.state` | phone | Reports its calls (needs the phone permission) |
+| `call.control` | phone | Answers, declines and silences calls when a PC asks |
+| `call.show` | PC | Shows calls |
+
+A phone reports calls only to PCs that offer `call.show`, and only while
+both devices allow it (the `calls` device toggle, on by default, on each
+side).
+
+## 2. Messages
+
+On the control stream.
+
+```
+t = "call.state" b = {
+ id: text, // The phone's ID for this call: 1–64 bytes, the same in each of its messages
+ state: "ringing" | "active" | "ended",
+ ? incoming: bool, // Default true; false for calls the phone's user made
+ ? number: text, // At most 256 bytes, when the phone knows it
+ ? name: text, // The contact's name, when the number is a contact
+ ? photo: bytes, // The contact's photo, a JPEG of at most 64 KiB, with "ringing"
+ ? missed: bool, // With "ended": it rang and nobody answered (default false)
+}
+t = "call.action" id = n b = { id: text, action: "answer" | "decline" | "silence" }
+t = "ok" re = n
+```
+
+### 2.1 `call.state`
+
+Sent when a call starts ringing (and again when the phone learns more,
+such as the number), when it's answered, and when it ends. Not answered.
+A PC that connects during a call gets its latest `call.state` right away.
+
+A call that was declined, on the phone or from a PC, ends without
+`missed`.
+
+### 2.2 `call.action`
+
+- `answer`: answers the ringing call; the conversation happens on the phone.
+- `decline`: declines the ringing call, or hangs up the active one.
+- `silence`: stops the phone ringing; the call still rings for the caller.
+
+Errors: `NOT_FOUND` when `id` isn't the call in progress (or, for `answer`
+and `silence`, it no longer rings); `DENIED` when calls are off for the
+PC; `UNSUPPORTED` when the phone doesn't offer `call.control`.
+
+## 3. Privacy
+
+Numbers, names and photos are never logged (v0 §11).
diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.md
index 958ad50..4ad6807 100644
--- a/docs/protocol/capabilities.md
+++ b/docs/protocol/capabilities.md
@@ -36,7 +36,8 @@ capability is missing.
| `notify.sensitive` | Forwards notifications Android hides as sensitive (e.g. one-time codes) | Elevated |
| `sms.read` | Reads SMS conversations | SMS permission |
| `sms.send` | Sends SMS | SMS permission |
-| `call.state` | Reports incoming and ongoing calls | phone permission |
+| `call.state` | Reports incoming and ongoing calls ([calls](calls.md)) | phone permission |
+| `call.control` | Answers, declines and silences calls when a PC asks ([calls](calls.md)) | phone permission |
| `clip.write` | Accepts clipboard content from the PC ([clipboard service](clipboard.md)) | app update |
| `clip.share` | Sends the clipboard when the user taps "Send" | app update |
| `clip.read.auto` | Sends clipboard changes automatically, in the background | Elevated |
@@ -54,6 +55,7 @@ capability is missing.
|---|---|---|
| `pc.power` | Locks or sleeps on request ([actions](actions.md)) | app update |
| `photos.show` | Shows a phone's new photos ([photos](photos.md)) | app update |
+| `call.show` | Shows a phone's calls ([calls](calls.md)) | app update |
| `files.browse` | Lets a paired phone browse and fetch its files | app update |
| `input.inject` | Accepts pointer and keyboard input (touchpad, air mouse, voice typing) | app update |
| `deck.actions` | Runs Deck actions | app update |