Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Calls in progress on the PC: hang up, mute, speaker, hold, keypad
Beecefaf490f9a6
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex c6dcb71..623c6a6 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -38,6 +38,14 @@<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" />+ <!-- Controlling the call in progress for a PC (mute, speaker, hold,+ keypad) as a calling companion, without being the phone app. -->+ <uses-permission android:name="android.permission.CALL_COMPANION_APP" />+ <!-- The same, through the app-op the shell grants at Elevated: Telecom+ binds a companion that has it. -->+ <uses-permission+ android:name="android.permission.MANAGE_ONGOING_CALLS"+ tools:ignore="ProtectedPermissions" /><!-- Calls and texts need a phone line, but tablets without one stillrun everything else. --><uses-feature@@ -191,6 +199,16 @@android:name=".elevated.PairingNotification$Receiver"android:exported="false" />+ <!-- Telecom binds it while there are calls (CALL_COMPANION_APP). -->+ <service+ android:name=".calls.CallCompanion"+ android:exported="true"+ android:permission="android.permission.BIND_INCALL_SERVICE">+ <intent-filter>+ <action android:name="android.telecom.InCallService" />+ </intent-filter>+ </service>+<serviceandroid:name=".mirror.MirrorService"android:exported="false"diff --git a/android/app/src/main/kotlin/app/nectarlink/android/calls/CallCompanion.kt b/android/app/src/main/kotlin/app/nectarlink/android/calls/CallCompanion.ktnew file mode 100644index 0000000..0b082aa--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/calls/CallCompanion.kt@@ -0,0 +1,143 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.calls++import android.app.AppOpsManager+import android.content.Context+import android.os.Build+import android.os.Process+import android.telecom.Call+import android.telecom.CallAudioState+import android.telecom.InCallService+import android.telecom.VideoProfile+import app.nectarlink.core.CallControls++/**+ * Nectarlink as a calling companion: Telecom binds this while there are+ * calls, without Nectarlink being the phone app, so a PC can mute, switch to+ * the speaker, hold, and press keys on the call in progress. It shows+ * nothing on the phone. Telecom binds companions that hold+ * MANAGE_ONGOING_CALLS (Android 12+), an app-op Elevated's shell grants.+ */+class CallCompanion : InCallService() {+ /** The call being controlled: the active one, or the latest. */+ private var call: Call? = null++ private val callback = object : Call.Callback() {+ override fun onStateChanged(call: Call, state: Int) = changed()+ override fun onDetailsChanged(call: Call, details: Call.Details) = changed()+ }++ override fun onCreate() {+ super.onCreate()+ instance = this+ }++ override fun onDestroy() {+ if (instance === this) instance = null+ super.onDestroy()+ }++ override fun onCallAdded(call: Call) {+ call.registerCallback(callback)+ this.call = call+ changed()+ }++ override fun onCallRemoved(call: Call) {+ call.unregisterCallback(callback)+ if (this.call === call) this.call = calls.lastOrNull { it !== call }+ changed()+ }++ @Deprecated("Deprecated in Java")+ override fun onCallAudioStateChanged(audioState: CallAudioState?) = changed()++ /** Only a call in progress has controls; ringing and ending report themselves. */+ private fun changed() {+ val state = call?.stateNow()+ if (state == Call.STATE_ACTIVE || state == Call.STATE_HOLDING) PhoneCalls.controlsChanged()+ }++ private fun controls(): CallControls? {+ val call = call ?: return null+ @Suppress("DEPRECATION")+ val audio = callAudioState ?: return null+ return CallControls(+ muted = audio.isMuted,+ speaker = audio.route == CallAudioState.ROUTE_SPEAKER,+ held = call.stateNow() == Call.STATE_HOLDING,+ canHold = call.details.can(Call.Details.CAPABILITY_HOLD),+ )+ }++ private fun answer(): Boolean {+ val call = call?.takeIf { it.stateNow() == Call.STATE_RINGING } ?: return false+ call.answer(VideoProfile.STATE_AUDIO_ONLY)+ return true+ }++ private fun hangUp(): Boolean {+ val call = call ?: return false+ if (call.stateNow() == Call.STATE_RINGING) call.reject(false, null) else call.disconnect()+ return true+ }++ @Suppress("DEPRECATION") // setAudioRoute: still how a companion picks the speaker.+ private fun speaker(on: Boolean) {+ setAudioRoute(if (on) CallAudioState.ROUTE_SPEAKER else CallAudioState.ROUTE_WIRED_OR_EARPIECE)+ }++ private fun hold(on: Boolean): Boolean {+ val call = call ?: return false+ if (on) call.hold() else call.unhold()+ return true+ }++ private fun dtmf(digit: Char): Boolean {+ val call = call ?: return false+ call.playDtmfTone(digit)+ call.stopDtmfTone()+ return true+ }++ companion object {+ @Volatile private var instance: CallCompanion? = null++ /** Whether Telecom has bound it (there's a call, and the phone allows companions). */+ val bound: Boolean get() = instance != null++ /** Whether Telecom will bind it: Android 12+, with the app-op allowed. */+ fun allowed(context: Context): Boolean {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return false+ val ops = context.getSystemService(AppOpsManager::class.java) ?: return false+ return runCatching {+ // Deprecated on 37 for attribution-aware checks; this one is only the app's own.+ @Suppress("DEPRECATION")+ ops.unsafeCheckOpNoThrow(OP, Process.myUid(), context.packageName) == AppOpsManager.MODE_ALLOWED+ }.getOrDefault(false)+ }++ /** The app-op's name for `appops set`. */+ const val OP_NAME = "MANAGE_ONGOING_CALLS"+ private const val OP = "android:manage_ongoing_calls"++ /** The call in progress' mute, speaker and hold, when bound. */+ fun controls(): CallControls? = instance?.controls()++ fun answer(): Boolean = instance?.answer() ?: false++ fun hangUp(): Boolean = instance?.hangUp() ?: false++ fun mute(on: Boolean): Boolean = instance?.run { setMuted(on); true } ?: false++ fun speaker(on: Boolean): Boolean = instance?.run { speaker(on); true } ?: false++ fun hold(on: Boolean): Boolean = instance?.hold(on) ?: false++ fun dtmf(digit: Char): Boolean = instance?.dtmf(digit) ?: false+ }+}++/** The call's state: `Details.getState` from Android 12, `getState` before. */+private fun Call.stateNow(): Int =+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) details.state else @Suppress("DEPRECATION") statediff --git a/android/app/src/main/kotlin/app/nectarlink/android/calls/PhoneCalls.kt b/android/app/src/main/kotlin/app/nectarlink/android/calls/PhoneCalls.ktindex c335f61..28d8502 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/calls/PhoneCalls.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/calls/PhoneCalls.kt@@ -50,9 +50,12 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unitvar answered: Boolean = false,/** Declined from a PC: not a missed call. */var declined: Boolean = false,+ /** When it was answered (Unix ms). */+ var since: Long? = null,)fun start() {+ instance = thisif (receiver != null || !canFollow(context)) returnreceiver = object : BroadcastReceiver() {override fun onReceive(context: Context, intent: Intent) {@@ -98,12 +101,14 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> UnitTelephonyManager.EXTRA_STATE_OFFHOOK -> when {call == null -> {// Calling out.- val tracked = Tracked(id = System.currentTimeMillis().toString(), incoming = false, number = number, answered = true)+ val now = System.currentTimeMillis()+ val tracked = Tracked(id = now.toString(), incoming = false, number = number, answered = true, since = now)current = trackedreport(tracked, CallPhase.ACTIVE, withContact = false)}!call.answered -> {call.answered = true+ call.since = System.currentTimeMillis()report(call, CallPhase.ACTIVE, withContact = false)}}@@ -125,10 +130,19 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unit// A snapshot: the call may change while this waits its turn.val number = call.numberval incoming = call.incoming- worker.execute { send(call.id, phase, incoming, number, withContact, missedCheck) }+ val since = call.since+ worker.execute { send(call.id, phase, incoming, number, since, withContact, missedCheck) }}- private fun send(id: String, phase: CallPhase, incoming: Boolean, number: String?, withContact: Boolean, missedCheck: Boolean) {+ private fun send(+ id: String,+ phase: CallPhase,+ incoming: Boolean,+ number: String?,+ since: Long?,+ withContact: Boolean,+ missedCheck: Boolean,+ ) {val (name, photo) = if (withContact) contact(number) else null to nullval missed = missedCheck && wasMissed()onChange(@@ -140,10 +154,19 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unitname = name,photo = photo.takeIf { phase == CallPhase.RINGING },missed = missed,+ since = since.takeIf { phase == CallPhase.ACTIVE },+ controls = if (phase == CallPhase.ACTIVE) CallCompanion.controls() else null,),)}+ /** The companion's mute, speaker or hold changed: PCs hear of it. */+ private fun resendActive() {+ main.post {+ current?.takeIf { it.answered }?.let { report(it, CallPhase.ACTIVE, withContact = true) }+ }+ }+/** 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@@ -188,33 +211,58 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unit}.getOrDefault(true)}- /** Runs what a PC asked; false if the phone couldn't. */+ /**+ * Runs what a PC asked; false if the phone couldn't. The companion+ * (when Telecom has bound it) controls the call itself; otherwise+ * Telecom answers and ends it, and in-call controls aren't there.+ */@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 falsereturn 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+ CallCommand.Answer -> CallCompanion.answer() || telecom()?.let {+ // Deprecated for dialer apps, which get the call directly;+ // still how any other app answers one.@Suppress("DEPRECATION")- if (!telecom.endCall()) return false+ it.acceptRingingCall()+ true+ } == true+ CallCommand.Decline -> {+ call.declined = !call.answered+ CallCompanion.hangUp() || hangUpWithTelecom()+ }+ CallCommand.Silence -> telecom()?.let { silence(it); true } == true+ is CallCommand.Mute -> CallCompanion.mute(command.on)+ is CallCommand.Speaker -> CallCompanion.speaker(command.on)+ is CallCommand.Hold -> CallCompanion.hold(command.on)+ is CallCommand.Dtmf -> command.digit.singleOrNull()?.let(CallCompanion::dtmf) ?: false+ is CallCommand.Volume -> {+ context.getSystemService(AudioManager::class.java).adjustStreamVolume(+ AudioManager.STREAM_VOICE_CALL,+ if (command.up) AudioManager.ADJUST_RAISE else AudioManager.ADJUST_LOWER,+ 0,+ )+ true}- CallCommand.SILENCE -> silence(telecom)}- true}.getOrElse {Log.w(TAG, "a call action failed", it)false}}+ /** Telecom, when the app may answer and end calls. */+ private fun telecom(): TelecomManager? =+ context.getSystemService(TelecomManager::class.java)?.takeIf { granted(context, Manifest.permission.ANSWER_PHONE_CALLS) }++ @SuppressLint("MissingPermission")+ private fun hangUpWithTelecom(): Boolean {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return false+ @Suppress("DEPRECATION")+ return telecom()?.endCall() == true+ }+private var mutedRinger = false@SuppressLint("MissingPermission")@@ -240,6 +288,13 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unitcompanion object {private const val TAG = "PhoneCalls"++ @Volatile private var instance: PhoneCalls? = null++ /** The companion's view of the call changed (mute, speaker, hold). */+ internal fun controlsChanged() {+ instance?.resendActive()+ }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 = 1500Ldiff --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 e343718..ddc5fe6 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.ReceivedFilesimport app.nectarlink.android.files.TransferNotificationsimport app.nectarlink.android.Rimport app.nectarlink.android.notifications.NotificationListener+import app.nectarlink.android.calls.CallCompanionimport app.nectarlink.android.calls.PhoneCallsimport app.nectarlink.android.elevated.Elevatedimport app.nectarlink.android.mirror.InputService@@ -383,6 +384,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener(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()) ++ (if (PhoneCalls.canControl(context) && CallCompanion.allowed(context)) listOf("call.incall") else emptyList()) +(if (PhoneSms.canRead(context)) listOf("sms.read") else emptyList()) +(if (PhoneSms.canSend(context)) listOf("sms.send") else emptyList()) +(if (InputService.running || Elevated.running) listOf("mirror.input") else emptyList())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 c8fe75c..48f2b31 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@@ -10,6 +10,7 @@ import android.util.Logimport android.view.KeyEventimport android.view.WindowManagerimport androidx.core.content.edit+import app.nectarlink.android.calls.CallCompanionimport app.nectarlink.core.MirrorInputEventimport app.nectarlink.core.TouchPhaseimport io.github.muntashirakon.adb.AbsAdbConnectionManager@@ -182,6 +183,11 @@ object Elevated {if (context.checkSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS) != PackageManager.PERMISSION_GRANTED) {run(adb, "pm grant ${context.packageName} ${Manifest.permission.WRITE_SECURE_SETTINGS}")}+ // Lets Telecom bind the calling companion: mute, speaker, hold and+ // the keypad from a PC.+ if (!CallCompanion.allowed(context) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+ run(adb, "appops set ${context.packageName} ${CallCompanion.OP_NAME} 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"diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex 88a245a..3d7f27d 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -77,7 +77,7 @@<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><string name="elevated_title">Real touch and keys (Wireless debugging)</string>- <string name="elevated_not_set_up">Drag in real time and use every key. Uses the phone\'s own Wireless debugging; nothing else to install.</string>+ <string name="elevated_not_set_up">Drag in real time, use every key, and mute, hold or use the keypad on calls from a PC. Uses the phone\'s own Wireless debugging; nothing else to install.</string><string name="elevated_waiting">Set up. Waiting for Wireless debugging: turn it on in Developer options (Nectarlink turns it on by itself after the first time).</string><string name="elevated_starting">Starting…</string><string name="elevated_running">On: your PC\'s mouse and keyboard work like a real touchscreen and keyboard.</string>diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex 9db0e96..135ba03 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -198,6 +198,23 @@ enum Command {/// Act as a phone with a few sample conversations (use with --as-phone),/// so a PC can read them and text through this client; stays online.Texts,+ /// Act as a phone with an incoming call (use with --as-phone): PCs can+ /// answer it, then mute, use the speaker, hold, press keys or hang up,+ /// as on a phone that controls its calls. Stays online.+ IncomingCall {+ /// The caller's number.+ #[arg(default_value = "+15550144")]+ number: String,+ /// The caller's name, as in contacts.+ #[arg(long)]+ caller: Option<String>,+ /// Without the in-call controls (`call.incall`): only answer and end.+ #[arg(long)]+ basic: bool,+ /// Already answered on the phone: the call is in progress.+ #[arg(long)]+ answered: bool,+ },/// A paired phone's text messages: list conversations, show one, or send.Sms {device: String,@@ -209,6 +226,12 @@ enum Command {Calls {#[arg(long, value_enum)]auto: Option<CallArg>,+ /// With the first ringing call, run these actions in order, comma+ /// separated: answer, decline, silence, mute, unmute, speaker,+ /// earpiece, hold, unhold, up, down, a keypad key (0-9, *, #), or+ /// wait:N (seconds).+ #[arg(long)]+ script: Option<String>,},/// 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.@@ -404,6 +427,12 @@ fn sample_texts() {.collect();}+/// The call `incoming-call` pretends to have, and how to tell PCs it changed.+static CALL: std::sync::Mutex<Option<nectarlink_core::CallState>> = std::sync::Mutex::new(None);+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);+/// 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";@@ -497,6 +526,52 @@ impl Platform for TerminalPlatform {}Ok(())}+ fn call_command(+ &self,+ id: &str,+ command: nectarlink_core::CallCommand,+ ) -> std::result::Result<(), String> {+ use nectarlink_core::CallCommand as C;+ let mut current = CALL.lock().unwrap();+ let call = current.as_mut().filter(|c| c.id == id).ok_or("no such call")?;+ let controls = call.controls.get_or_insert_default();+ match command {+ C::Answer => {+ controls.can_hold = true;+ call.state = "active".into();+ call.photo = None;+ call.since = Some(+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| d.as_millis() as i64),+ );+ }+ C::Decline => call.state = "ended".into(),+ C::Silence => println!("Silenced."),+ C::Mute(on) => controls.muted = on,+ C::Speaker(on) => controls.speaker = on,+ C::Hold(on) => controls.held = on,+ C::Dtmf(digit) => println!("Key {digit}."),+ C::Volume(up) => println!("Volume {}.", if up { "up" } else { "down" }),+ }+ println!("A PC asked: {command:?}.");+ // Only an answered call has controls, and only on a phone that offers them.+ if call.state != "active" || !CALL_CONTROLS.load(std::sync::atomic::Ordering::Relaxed) {+ call.controls = None;+ }+ let call = call.clone();+ if call.state == "ended" {+ *current = None;+ }+ if let Some(node) = CALL_NODE.get().cloned() {+ tokio::runtime::Handle::current().spawn(async move {+ if let Err(e) = node.call_changed(call).await {+ println!("Couldn't tell PCs: {e}");+ }+ });+ }+ Ok(())+ }fn open_photo(&self, id: &str) -> std::result::Result<nectarlink_core::OutgoingFile, String> {let path = PHOTO.get().filter(|_| id == PHOTO_ID).ok_or("no such photo")?;println!("A PC asked for the photo; sending it.");@@ -868,6 +943,37 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {println!("Sharing sample conversations with paired PCs.");watch(node, false).await?;}+ Command::IncomingCall { number, caller, basic, answered } => {+ if !cli.as_phone {+ bail!("calls are on phones: add --as-phone");+ }+ let _ = CALL_NODE.set(node.clone());+ let mut offers = cli.offers.clone();+ offers+ .extend([nectarlink_core::CALLS_STATE.to_owned(), nectarlink_core::CALLS_CONTROL.to_owned()]);+ CALL_CONTROLS.store(!*basic, std::sync::atomic::Ordering::Relaxed);+ if !*basic {+ offers.push(nectarlink_core::CALLS_IN_CALL.to_owned());+ }+ node.update_power(node_power(cli), offers).await;+ let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;+ let call = nectarlink_core::CallState {+ id: now.to_string(),+ state: if *answered { "active" } else { "ringing" }.into(),+ incoming: true,+ number: Some(number.clone()),+ name: caller.clone(),+ photo: None,+ missed: false,+ since: answered.then_some(now),+ controls: (*answered && !*basic)+ .then(|| nectarlink_core::CallControls { can_hold: true, ..Default::default() }),+ };+ *CALL.lock().unwrap() = Some(call.clone());+ node.call_changed(call).await.context("can't tell PCs")?;+ println!("Ringing on connected PCs (and on others when they connect).");+ watch(node, false).await?;+ }Command::Sms { device, action } => {let mut offers = cli.offers.clone();offers.push(nectarlink_core::SMS_SHOW.into());@@ -917,7 +1023,7 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {}}}- Command::Calls { auto } => {+ Command::Calls { auto, script } => {let mut offers = cli.offers.clone();offers.push(nectarlink_core::CALLS_SHOW.into());node.update_power(node_power(cli), offers).await;@@ -928,8 +1034,45 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {});let mut events = node.events();let answerer = node.clone();+ let mut script = script.clone();tokio::spawn(async move {while let Ok(event) = events.recv().await {+ if let (Some(steps), NodeEvent::Call { device, call }) = (script.as_ref(), &event)+ && call.state == "ringing"+ && call.incoming+ {+ use nectarlink_core::CallCommand as C;+ for step in steps.split(',').map(str::trim) {+ let command = match step {+ "answer" => C::Answer,+ "decline" | "end" => C::Decline,+ "silence" => C::Silence,+ "mute" => C::Mute(true),+ "unmute" => C::Mute(false),+ "speaker" => C::Speaker(true),+ "earpiece" => C::Speaker(false),+ "hold" => C::Hold(true),+ "unhold" => C::Hold(false),+ "up" => C::Volume(true),+ "down" => C::Volume(false),+ s if s.starts_with("wait:") => {+ let secs = s[5..].parse().unwrap_or(1);+ tokio::time::sleep(std::time::Duration::from_secs(secs)).await;+ continue;+ }+ s if s.len() == 1 => C::Dtmf(s.chars().next().unwrap_or('0')),+ other => {+ println!("Unknown step {other}");+ continue;+ }+ };+ match answerer.call_command(*device, call.id.clone(), command).await {+ Ok(()) => println!("Did it: {command:?}."),+ Err(e) => println!("Couldn't {command:?}: {e}"),+ }+ }+ script = None;+ }if let (Some(command), NodeEvent::Call { device, call }) = (command, &event)&& call.state == "ringing"&& call.incoming@@ -1302,12 +1445,14 @@ fn print_event(node: &Node, event: &NodeEvent) {(None, Some(num)) => format!(" from {num}"),_ => String::new(),},- if call.missed {- ", missed"- } else if call.photo.is_some() {- ", with photo"- } else {- ""+ match (call.missed, call.photo.is_some(), call.controls) {+ (true, ..) => ", missed".to_owned(),+ (_, _, Some(c)) => format!(+ " [muted {}, speaker {}, held {}, can hold {}]",+ c.muted, c.speaker, c.held, c.can_hold+ ),+ (_, true, _) => ", with photo".to_owned(),+ _ => String::new(),},),NodeEvent::PhotoAdded { device, photo } => println!(diff --git a/core/nectarlink-core/src/calls.rs b/core/nectarlink-core/src/calls.rsindex 5896ede..ef6ac36 100644--- a/core/nectarlink-core/src/calls.rs+++ b/core/nectarlink-core/src/calls.rs@@ -7,7 +7,7 @@ use std::sync::{Arc, Mutex};use nectarlink_protocol::{Envelope, ErrorCode,- messages::{CallAction, CallState, calls, types},+ messages::{CallAction, CallState, calls, is_dtmf_digit, types},};use crate::{Error, Result, events::NodeEvent, node::Shared, session::Session};@@ -23,6 +23,16 @@ pub enum CallCommand {Decline,/// Stops the ringing; the call still rings on for the caller.Silence,+ /// Mutes (true) or unmutes the phone's microphone on the call.+ Mute(bool),+ /// The speaker (true) or the earpiece.+ Speaker(bool),+ /// Puts the call on hold (true) or takes it off.+ Hold(bool),+ /// A keypad tone: `0`–`9`, `*` or `#`.+ Dtmf(char),+ /// The call's volume up (true) or down.+ Volume(bool),}impl CallCommand {@@ -31,17 +41,61 @@ impl CallCommand {CallCommand::Answer => calls::ANSWER,CallCommand::Decline => calls::DECLINE,CallCommand::Silence => calls::SILENCE,+ CallCommand::Mute(true) => calls::MUTE,+ CallCommand::Mute(false) => calls::UNMUTE,+ CallCommand::Speaker(true) => calls::SPEAKER,+ CallCommand::Speaker(false) => calls::EARPIECE,+ CallCommand::Hold(true) => calls::HOLD,+ CallCommand::Hold(false) => calls::UNHOLD,+ CallCommand::Dtmf(_) => calls::DTMF,+ CallCommand::Volume(true) => calls::VOLUME_UP,+ CallCommand::Volume(false) => calls::VOLUME_DOWN,}}- pub fn parse(action: &str) -> Option<CallCommand> {- match action {- calls::ANSWER => Some(CallCommand::Answer),- calls::DECLINE => Some(CallCommand::Decline),- calls::SILENCE => Some(CallCommand::Silence),+ /// The command for an action (and, for `dtmf`, its digit).+ pub fn parse(action: &str, digit: Option<&str>) -> Option<CallCommand> {+ Some(match action {+ calls::ANSWER => CallCommand::Answer,+ calls::DECLINE => CallCommand::Decline,+ calls::SILENCE => CallCommand::Silence,+ calls::MUTE => CallCommand::Mute(true),+ calls::UNMUTE => CallCommand::Mute(false),+ calls::SPEAKER => CallCommand::Speaker(true),+ calls::EARPIECE => CallCommand::Speaker(false),+ calls::HOLD => CallCommand::Hold(true),+ calls::UNHOLD => CallCommand::Hold(false),+ calls::DTMF => CallCommand::Dtmf(digit.filter(|d| is_dtmf_digit(d))?.chars().next()?),+ calls::VOLUME_UP => CallCommand::Volume(true),+ calls::VOLUME_DOWN => CallCommand::Volume(false),+ _ => return None,+ })+ }++ /// The `digit` field it goes with.+ fn digit(self) -> Option<String> {+ match self {+ CallCommand::Dtmf(c) => Some(c.to_string()),_ => None,}}++ /// Whether it applies to a call in `state` ("ringing" or "active"),+ /// and whether it needs the phone to control the call (`call.incall`).+ fn fits(self, state: &str) -> bool {+ match self {+ CallCommand::Answer | CallCommand::Silence => state == calls::RINGING,+ CallCommand::Decline => true,+ _ => state == calls::ACTIVE,+ }+ }++ fn needs_in_call(self) -> bool {+ matches!(+ self,+ CallCommand::Mute(_) | CallCommand::Speaker(_) | CallCommand::Hold(_) | CallCommand::Dtmf(_)+ )+ }}/// The phone's call in progress (ringing or active), for PCs that connect@@ -104,7 +158,8 @@ pub(crate) async fn command(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() })?;+ let action = CallAction { id, action: command.as_str().into(), digit: command.digit() };+ let env = Envelope::new(types::CALL_ACTION, &action)?;session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect(types::OK)?;Ok(())}@@ -122,19 +177,20 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &EOk(true)}types::CALL_ACTION => {- let CallAction { id, action } = env.body()?;+ let CallAction { id, action, digit } = env.body()?;let current = shared.calls.get();+ let offers = |cap: &str| shared.local_capabilities().iter().any(|c| c == cap);+ let command = CallCommand::parse(&action, digit.as_deref());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 if !offers(calls::CONTROL)+ || command.is_some_and(|c| c.needs_in_call() && !offers(calls::IN_CALL))+ {+ Envelope::error(ErrorCode::Unsupported, "this phone doesn't take that call action")} else {- match (CallCommand::parse(&action), current) {+ match (command, current) {(None, _) => Envelope::error(ErrorCode::Unsupported, "unknown action"),- (Some(command), Some(call))- if call.id == id- && (call.state == calls::RINGING || command == CallCommand::Decline) =>- {+ (Some(command), Some(call)) if call.id == id && command.fits(&call.state) => {let platform = shared.platform.clone();match tokio::task::spawn_blocking(move || platform.call_command(&id, command)).await@@ -163,10 +219,35 @@ mod tests {#[test]fn commands_round_trip() {- for c in [CallCommand::Answer, CallCommand::Decline, CallCommand::Silence] {- assert_eq!(CallCommand::parse(c.as_str()), Some(c));+ let all = [+ CallCommand::Answer,+ CallCommand::Decline,+ CallCommand::Silence,+ CallCommand::Mute(true),+ CallCommand::Mute(false),+ CallCommand::Speaker(true),+ CallCommand::Speaker(false),+ CallCommand::Hold(true),+ CallCommand::Hold(false),+ CallCommand::Dtmf('#'),+ CallCommand::Volume(true),+ CallCommand::Volume(false),+ ];+ for c in all {+ assert_eq!(CallCommand::parse(c.as_str(), c.digit().as_deref()), Some(c));}- assert_eq!(CallCommand::parse("hold"), None);+ assert_eq!(CallCommand::parse("transfer", None), None);+ assert_eq!(CallCommand::parse("dtmf", Some("12")), None);+ assert_eq!(CallCommand::parse("dtmf", Some("x")), None);+ assert_eq!(CallCommand::parse("dtmf", None), None);+ }++ #[test]+ fn commands_fit_the_call() {+ assert!(CallCommand::Answer.fits("ringing") && !CallCommand::Answer.fits("active"));+ assert!(CallCommand::Mute(true).fits("active") && !CallCommand::Mute(true).fits("ringing"));+ assert!(CallCommand::Decline.fits("ringing") && CallCommand::Decline.fits("active"));+ assert!(CallCommand::Volume(true).fits("active") && !CallCommand::Volume(true).needs_in_call());}#[test]@@ -180,6 +261,8 @@ mod tests {name: None,photo: None,missed: false,+ since: None,+ controls: None,};current.set(&call);assert_eq!(current.get().map(|c| c.id), Some("7".into()));diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsindex 71d640d..c8d8e12 100644--- a/core/nectarlink-core/src/lib.rs+++ b/core/nectarlink-core/src/lib.rs@@ -42,10 +42,12 @@ pub use nectarlink_protocol::messages::clip::{pub use nectarlink_protocol::{DeviceId, PacketKind,messages::{- Battery, CLIP_MAX_BYTES, CallState, DeviceInfo, DeviceKind, MediaPlayer, MirrorConfig, MirrorInput,- MirrorStart, Notification, NotificationAction, PhotoNew as Photo, PowerLevel, SmsMessage, SmsPart,- SmsThread, TouchAction,- calls::{CONTROL as CALLS_CONTROL, SHOW as CALLS_SHOW, STATE as CALLS_STATE},+ Battery, CLIP_MAX_BYTES, CallControls, CallState, DeviceInfo, DeviceKind, MediaPlayer, MirrorConfig,+ MirrorInput, MirrorStart, Notification, NotificationAction, PhotoNew as Photo, PowerLevel,+ SmsMessage, SmsPart, SmsThread, TouchAction,+ calls::{+ CONTROL as CALLS_CONTROL, IN_CALL as CALLS_IN_CALL, SHOW as CALLS_SHOW, STATE as CALLS_STATE,+ },mirror::{CAPTURE as MIRROR_CAPTURE, INPUT as MIRROR_INPUT, MAX_TEXT_BYTES as MIRROR_MAX_TEXT_BYTES,VIEW as MIRROR_VIEW,diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex 31ff25d..d12c6ac 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -1158,6 +1158,8 @@ async fn calls_show_on_the_pc_which_can_answer_them() {name: Some("Sam".into()),photo: Some(vec![0xff, 0xd8]),missed: false,+ since: None,+ controls: None,};// The call in `state` (a PC that just connected may hear the earlier// one again).@@ -1189,6 +1191,28 @@ async fn calls_show_on_the_pc_which_can_answer_them() {pc.node.call_command(phone_id, "c1".into(), CallCommand::Silence).await,Err(Error::NotFound)));+ // The volume works on any phone; mute needs one that controls the call.+ pc.node.call_command(phone_id, "c1".into(), CallCommand::Volume(true)).await.unwrap();+ assert!(matches!(+ pc.node.call_command(phone_id, "c1".into(), CallCommand::Mute(true)).await,+ Err(Error::Unsupported)+ ));+ phone+ .node+ .update_power(+ PowerLevel::NotApplicable,+ vec![+ "media.control".into(),+ nectarlink_core::CALLS_STATE.into(),+ nectarlink_core::CALLS_CONTROL.into(),+ nectarlink_core::CALLS_IN_CALL.into(),+ ],+ )+ .await;+ pc.node.call_command(phone_id, "c1".into(), CallCommand::Mute(true)).await.unwrap();+ pc.node.call_command(phone_id, "c1".into(), CallCommand::Dtmf('5')).await.unwrap();+ let seen: Vec<CallCommand> = phone.platform.calls.lock().unwrap().iter().map(|(_, c)| *c).collect();+ assert_eq!(seen[1..], [CallCommand::Volume(true), CallCommand::Mute(true), CallCommand::Dtmf('5')]);pc.node.call_command(phone_id, "c1".into(), CallCommand::Decline).await.unwrap();let ended = CallState { state: "ended".into(), ..active };diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex d6251b5..713d47a 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -636,6 +636,19 @@ pub struct Call {pub photo: Option<Vec<u8>>,/// With `Ended`: it rang and nobody answered.pub missed: bool,+ /// With `Active`: when it was answered, in Unix milliseconds.+ pub since: Option<i64>,+ /// With `Active`, when this app controls the call (its in-call service+ /// is bound): mute, speaker and hold.+ pub controls: Option<CallControls>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Record)]+pub struct CallControls {+ pub muted: bool,+ pub speaker: bool,+ pub held: bool,+ pub can_hold: bool,}/// Never prints the number, name or photo (protocol v0 §11).@@ -653,13 +666,33 @@ pub enum CallPhase {}/// What a PC asked of a call.-#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]pub enum CallCommand {Answer,/// Decline a ringing call, or hang up an active one.Decline,/// Stop the ringing.Silence,+ /// Mute (true) or unmute the microphone on the call.+ Mute {+ on: bool,+ },+ /// The speaker (true) or the earpiece.+ Speaker {+ on: bool,+ },+ /// Put the call on hold (true) or take it off.+ Hold {+ on: bool,+ },+ /// A keypad tone: "0"–"9", "*" or "#".+ Dtmf {+ digit: String,+ },+ /// The call's volume up (true) or down.+ Volume {+ up: bool,+ },}/// A photo or screenshot that just appeared on this phone@@ -1317,6 +1350,11 @@ impl core::Platform for PlatformAdapter {core::CallCommand::Answer => CallCommand::Answer,core::CallCommand::Decline => CallCommand::Decline,core::CallCommand::Silence => CallCommand::Silence,+ core::CallCommand::Mute(on) => CallCommand::Mute { on },+ core::CallCommand::Speaker(on) => CallCommand::Speaker { on },+ core::CallCommand::Hold(on) => CallCommand::Hold { on },+ core::CallCommand::Dtmf(digit) => CallCommand::Dtmf { digit: digit.to_string() },+ core::CallCommand::Volume(up) => CallCommand::Volume { up },};if self.0.call_command(id.to_owned(), command) { Ok(()) } else { Err("the phone couldn't".into()) }}@@ -1651,6 +1689,13 @@ impl NectarlinkNode {name: call.name,photo: call.photo,missed: call.missed,+ since: call.since,+ controls: call.controls.map(|c| core::CallControls {+ muted: c.muted,+ speaker: c.speaker,+ held: c.held,+ can_hold: c.can_hold,+ }),};self.run(async move { Ok(node.call_changed(call).await?) }).await}diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex 8e4d51c..a9ae6eb 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -783,6 +783,9 @@ pub mod calls {pub const CONTROL: &str = "call.control";/// Offered by PCs that show calls.pub const SHOW: &str = "call.show";+ /// Offered by phones that control a call in progress (mute, speaker,+ /// hold, keypad) when a PC asks.+ pub const IN_CALL: &str = "call.incall";/// 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;@@ -795,6 +798,30 @@ pub mod calls {pub const ANSWER: &str = "answer";pub const DECLINE: &str = "decline";pub const SILENCE: &str = "silence";+ pub const MUTE: &str = "mute";+ pub const UNMUTE: &str = "unmute";+ pub const SPEAKER: &str = "speaker";+ pub const EARPIECE: &str = "earpiece";+ pub const HOLD: &str = "hold";+ pub const UNHOLD: &str = "unhold";+ /// A keypad tone: `digit` is one of `0`–`9`, `*`, `#`.+ pub const DTMF: &str = "dtmf";+ pub const VOLUME_UP: &str = "volume_up";+ pub const VOLUME_DOWN: &str = "volume_down";+}++/// A call in progress, as the phone controls it (with `call.incall`).+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+pub struct CallControls {+ #[serde(default)]+ pub muted: bool,+ #[serde(default)]+ pub speaker: bool,+ #[serde(default)]+ pub held: bool,+ /// The call can be put on hold.+ #[serde(default)]+ pub can_hold: bool,}/// Body of `call.state`: a call on the phone started ringing, was@@ -820,6 +847,13 @@ pub struct CallState {/// With `ended`: it rang and nobody answered.#[serde(default)]pub missed: bool,+ /// With `active`: when it was answered, in Unix milliseconds.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub since: Option<i64>,+ /// With `active`, when the phone controls the call: its mute, speaker+ /// and hold.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub controls: Option<CallControls>,}fn yes() -> bool {@@ -854,6 +888,14 @@ impl CallState {pub struct CallAction {pub id: String,pub action: String,+ /// With `dtmf`: the key.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub digit: Option<String>,+}++/// Whether `digit` is a keypad key (`0`–`9`, `*`, `#`).+pub fn is_dtmf_digit(digit: &str) -> bool {+ digit.len() == 1 && digit.chars().all(|c| c.is_ascii_digit() || c == '*' || c == '#')}// ---- Photos (docs/protocol/photos.md) ----@@ -1279,6 +1321,8 @@ mod tests {name: Some("Sam".into()),photo: Some(vec![0xff, 0xd8]),missed: false,+ since: None,+ controls: None,};assert!(call.is_valid());let shown = format!("{call:?}");diff --git a/desktop/app/build.rs b/desktop/app/build.rsindex 7b0995e..2feebb8 100644--- a/desktop/app/build.rs+++ b/desktop/app/build.rs@@ -21,6 +21,7 @@ const QML: &[&str] = &["qml/MirrorWindow.qml","qml/components/Avatar.qml","qml/components/Button.qml",+ "qml/components/CallCard.qml","qml/components/CaptionButtons.qml","qml/components/Card.qml","qml/components/Chip.qml",@@ -197,6 +198,7 @@ fn main() {.files(["src/bridge/native.rs","src/bridge/app.rs",+ "src/bridge/calls.rs","src/bridge/devices.rs","src/bridge/history.rs","src/bridge/media.rs",diff --git a/desktop/app/qml/Icons.qml b/desktop/app/qml/Icons.qmlindex fd52f63..8fc2729 100644--- a/desktop/app/qml/Icons.qml+++ b/desktop/app/qml/Icons.qml@@ -27,6 +27,12 @@ QtObject {readonly property string music: "M9 18V5l12-2v13M9 18a3 3 0 1 1-6 0 3 3 0 0 1 6 0zM21 16a3 3 0 1 1-6 0 3 3 0 0 1 6 0z"readonly property string ring: "M6 8a6 6 0 1 1 12 0c0 7 3 8 3 8H3s3-1 3-8M10 20a2 2 0 0 0 4 0M2 8c0-2 1-4 2-5M22 8c0-2-1-4-2-5"readonly property string mic: "M12 2a3 3 0 0 1 3 3v6a3 3 0 0 1-6 0V5a3 3 0 0 1 3-3zM5 11a7 7 0 0 0 14 0M12 18v4"+ readonly property string micOff: "M15 10V5a3 3 0 0 0-5.8-1.1M9 9v2a3 3 0 0 0 4.9 2.3M5 11a7 7 0 0 0 11.3 5.5M19 11a7 7 0 0 1-.6 2.8M12 18v4M3 3l18 18"+ readonly property string speaker: "M4 9h3.5L12 5v14l-4.5-4H4zM15.5 9a4 4 0 0 1 0 6M18.5 6.5a8 8 0 0 1 0 11"+ readonly property string volumeUp: "M4 9h3.5L12 5v14l-4.5-4H4zM16 12h5M18.5 9.5v5"+ readonly property string volumeDown: "M4 9h3.5L12 5v14l-4.5-4H4zM16 12h5"+ readonly property string dialpad: "M6 4.5h.01M12 4.5h.01M18 4.5h.01M6 10h.01M12 10h.01M18 10h.01M6 15.5h.01M12 15.5h.01M18 15.5h.01M12 21h.01"+ readonly property string callEnd: "M2.5 14.5l1.8 2.2a1 1 0 0 0 1.3.2l2.9-1.8a1 1 0 0 0 .5-.9v-2.4a12 12 0 0 1 6 0v2.4a1 1 0 0 0 .5.9l2.9 1.8a1 1 0 0 0 1.3-.2l1.8-2.2a1 1 0 0 0 0-1.3C17.5 9 6.5 9 2.5 13.2a1 1 0 0 0 0 1.3z"readonly property string lock: "M7 11h10a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2zM8 11V8a4 4 0 0 1 8 0v3"readonly property string mark: "M12 2.5l8.2 4.75v9.5L12 21.5l-8.2-4.75v-9.5zM9 12h6"readonly property string back: "M15 6l-6 6 6 6"diff --git a/desktop/app/qml/components/CallCard.qml b/desktop/app/qml/components/CallCard.qmlnew file mode 100644index 0000000..5f3d5e2--- /dev/null+++ b/desktop/app/qml/components/CallCard.qml@@ -0,0 +1,261 @@+// SPDX-License-Identifier: GPL-3.0-or-later+import QtQuick+import app.nectarlink++// The call in progress on the phone: who, for how long, and its controls.+// The call's audio stays on the phone; these change what the phone does.+Card {+ id: card++ // Ticks once a second for the call's clock.+ property real now: Date.now()+ Timer {+ interval: 1000+ repeat: true+ running: card.visible && PhoneCall.since > 0+ triggeredOnStart: true+ onTriggered: card.now = Date.now()+ }+ property bool keypad: false+ // Keys pressed on this call, as the phone's keypad would show them.+ property string pressed: ""+ Connections {+ target: PhoneCall+ function onActiveChanged() {+ card.keypad = false+ card.pressed = ""+ }+ }++ function clock(ms) {+ const s = Math.max(0, Math.floor(ms / 1000))+ const h = Math.floor(s / 3600)+ const m = Math.floor((s % 3600) / 60)+ const ss = String(s % 60).padStart(2, "0")+ return h > 0 ? h + ":" + String(m).padStart(2, "0") + ":" + ss : m + ":" + ss+ }++ // A round toggle with its name under it.+ component Control: Column {+ id: control+ property string iconPath+ property string label+ property bool on: false+ signal clicked+ width: 60+ spacing: 6+ IconButton {+ anchors.horizontalCenter: parent.horizontalCenter+ width: 44; height: 44+ tonal: !control.on+ iconPath: control.iconPath+ label: control.label+ iconColor: control.on ? (Theme.graphite ? Theme.surface : Theme.primaryContent)+ : Theme.secondaryContainerContent+ Rectangle {+ z: -1+ anchors.fill: parent+ radius: width / 2+ visible: control.on+ color: Theme.graphite ? Theme.surfaceContent : Theme.primary+ }+ onClicked: control.clicked()+ }+ Txt {+ anchors.horizontalCenter: parent.horizontalCenter+ role: "caption"+ muted: !control.on+ text: control.label+ }+ }++ Column {+ width: parent.width+ spacing: 14++ Item {+ width: parent.width+ height: heading.height+ Txt { id: heading; text: qsTr("On a call"); role: "label"; muted: true }+ Txt {+ anchors.right: parent.right+ role: "label"+ color: PhoneCall.held ? Theme.warning : Theme.surfaceContentVariant+ text: PhoneCall.held ? qsTr("On hold")+ : PhoneCall.since > 0 ? card.clock(card.now - PhoneCall.since) : ""+ }+ }++ Row {+ width: parent.width+ spacing: 12+ Avatar {+ id: avatar+ anchors.verticalCenter: parent.verticalCenter+ width: 44; height: 44+ // A number alone has no letter worth showing.+ name: PhoneCall.number.length > 0 ? PhoneCall.caller : ""+ iconPath: PhoneCall.number.length > 0 ? "" : Icons.person+ emphasized: true+ }+ Column {+ anchors.verticalCenter: parent.verticalCenter+ width: parent.width - avatar.width - parent.spacing+ spacing: 2+ Txt {+ width: parent.width+ role: "title"+ text: PhoneCall.caller+ elide: Text.ElideRight+ }+ Txt {+ width: parent.width+ visible: text.length > 0+ role: "bodySmall"+ muted: true+ text: card.pressed.length > 0 ? card.pressed : PhoneCall.number+ elide: Text.ElideLeft+ }+ }+ }++ // ---- What the phone does on the call ----+ Row {+ visible: PhoneCall.controls+ anchors.horizontalCenter: parent.horizontalCenter+ spacing: 6+ Control {+ iconPath: PhoneCall.muted ? Icons.micOff : Icons.mic+ label: PhoneCall.muted ? qsTr("Muted") : qsTr("Mute")+ on: PhoneCall.muted+ onClicked: PhoneCall.setMute(!PhoneCall.muted)+ }+ Control {+ iconPath: Icons.speaker+ label: qsTr("Speaker")+ on: PhoneCall.speaker+ onClicked: PhoneCall.setSpeakerOn(!PhoneCall.speaker)+ }+ Control {+ visible: PhoneCall.canHold || PhoneCall.held+ iconPath: Icons.pause+ label: PhoneCall.held ? qsTr("Resume") : qsTr("Hold")+ on: PhoneCall.held+ onClicked: PhoneCall.setHold(!PhoneCall.held)+ }+ Control {+ iconPath: Icons.dialpad+ label: qsTr("Keypad")+ on: card.keypad+ onClicked: card.keypad = !card.keypad+ }+ }++ Grid {+ id: keys+ visible: PhoneCall.controls && card.keypad+ anchors.horizontalCenter: parent.horizontalCenter+ columns: 3+ columnSpacing: 10+ rowSpacing: 8+ Repeater {+ model: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "0", "#"]+ delegate: Rectangle {+ id: key+ required property string modelData+ width: 64; height: 40+ radius: Theme.pill(height)+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHighest+ border.width: Theme.graphite ? 1 : 0+ border.color: Theme.outlineVariant+ scale: keyTap.pressed ? Theme.pressScale : 1+ Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }+ function press() {+ PhoneCall.press(modelData)+ card.pressed = (card.pressed + modelData).slice(-24)+ }+ Accessible.role: Accessible.Button+ Accessible.name: modelData+ Accessible.onPressAction: press()+ Txt { anchors.centerIn: parent; role: "title"; text: key.modelData }+ HoverHandler { cursorShape: Qt.PointingHandCursor }+ TapHandler { id: keyTap; onTapped: key.press() }+ }+ }+ }++ Txt {+ width: parent.width+ visible: !PhoneCall.controls && PhoneCall.canEnd+ role: "caption"+ muted: true+ wrapMode: Text.WordWrap+ text: qsTr("Mute, the speaker and the keypad work from here once Wireless debugging is set up in Nectarlink on the phone (Android 12 or later).")+ }++ // ---- Volume and hanging up ----+ Row {+ visible: PhoneCall.canEnd+ anchors.horizontalCenter: parent.horizontalCenter+ spacing: 18+ IconButton {+ anchors.verticalCenter: parent.verticalCenter+ iconPath: Icons.volumeDown+ label: qsTr("Call volume down")+ onClicked: PhoneCall.volume(false)+ }+ FocusScope {+ id: end+ anchors.verticalCenter: parent.verticalCenter+ width: 72; height: 44+ activeFocusOnTab: true+ Accessible.role: Accessible.Button+ Accessible.name: qsTr("End call")+ Accessible.onPressAction: PhoneCall.end()+ Keys.onPressed: (event) => {+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {+ PhoneCall.end()+ event.accepted = true+ }+ }+ Rectangle {+ id: endBody+ anchors.fill: parent+ radius: Theme.pill(height)+ color: Theme.error+ scale: endTap.pressed ? Theme.pressScale : 1+ Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }+ Rectangle {+ anchors.fill: parent+ radius: parent.radius+ color: Theme.errorContent+ opacity: endTap.pressed ? 0.16 : (endHover.hovered ? 0.08 : 0)+ }+ Icon {+ anchors.centerIn: parent+ width: 22; height: 22+ path: Icons.callEnd+ color: Theme.errorContent+ }+ }+ Rectangle {+ anchors.fill: endBody+ anchors.margins: -3+ radius: endBody.radius + 3+ color: "transparent"+ border.width: 2+ border.color: Theme.primary+ visible: Theme.focusVisible(end)+ }+ HoverHandler { id: endHover; cursorShape: Qt.PointingHandCursor }+ TapHandler { id: endTap; onTapped: PhoneCall.end() }+ }+ IconButton {+ anchors.verticalCenter: parent.verticalCenter+ iconPath: Icons.volumeUp+ label: qsTr("Call volume up")+ onClicked: PhoneCall.volume(true)+ }+ }+ }+}diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qmlindex 97e01b5..802b865 100644--- a/desktop/app/qml/pages/HomePage.qml+++ b/desktop/app/qml/pages/HomePage.qml@@ -505,6 +505,13 @@ Item {width: home.sideWidthspacing: Theme.gutter+ // The call in progress on the phone.+ Binding { target: PhoneCall; property: "device"; value: home.deviceId; when: home.visible; restoreMode: Binding.RestoreNone }+ CallCard {+ width: home.sideWidth+ visible: PhoneCall.active && PhoneCall.device === home.deviceId+ }+// What plays on the phone (its first player).Repeater {model: MediaListdiff --git a/desktop/app/src/bridge/calls.rs b/desktop/app/src/bridge/calls.rsnew file mode 100644index 0000000..8b791df--- /dev/null+++ b/desktop/app/src/bridge/calls.rs@@ -0,0 +1,168 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! `PhoneCall`: the call in progress on the phone Home shows, and the+//! controls QML sends to it.++use std::pin::Pin;++use cxx_qt::{CxxQtType, Threading};+use cxx_qt_lib::QString;+use nectarlink_core::{CallCommand, DeviceId};++use crate::{calls, state::Changes};++#[cxx_qt::bridge]+pub mod qobject {+ unsafe extern "C++" {+ include!("cxx-qt-lib/qstring.h");+ type QString = cxx_qt_lib::QString;+ }++ unsafe extern "RustQt" {+ #[qobject]+ #[qml_element]+ #[qml_singleton]+ /// The phone whose call is shown (set by Home).+ #[qproperty(QString, device, READ, WRITE = set_device, NOTIFY)]+ /// A call is in progress on it.+ #[qproperty(bool, active)]+ /// Who's on the call, as well as the phone knows.+ #[qproperty(QString, caller)]+ /// The number, when there's a name to show above it.+ #[qproperty(QString, number)]+ /// When it was answered (Unix ms), or 0 when the phone didn't say.+ #[qproperty(f64, since)]+ /// The PC can end the call (and change the volume).+ #[qproperty(bool, can_end, cxx_name = "canEnd")]+ /// The phone controls the call for the PC: mute, speaker, hold, keypad.+ #[qproperty(bool, controls)]+ #[qproperty(bool, muted)]+ #[qproperty(bool, speaker)]+ #[qproperty(bool, held)]+ #[qproperty(bool, can_hold, cxx_name = "canHold")]+ type PhoneCall = super::PhoneCallRust;+ }++ impl cxx_qt::Threading for PhoneCall {}+ impl cxx_qt::Initialize for PhoneCall {}++ unsafe extern "RustQt" {+ #[cxx_name = "setDevice"]+ fn set_device(self: Pin<&mut PhoneCall>, device: QString);+ /// Hangs up.+ #[qinvokable]+ fn end(self: &PhoneCall);+ #[qinvokable]+ #[cxx_name = "setMute"]+ fn set_mute(self: &PhoneCall, on: bool);+ #[qinvokable]+ #[cxx_name = "setSpeakerOn"]+ fn set_speaker_on(self: &PhoneCall, on: bool);+ #[qinvokable]+ #[cxx_name = "setHold"]+ fn set_hold(self: &PhoneCall, on: bool);+ /// A keypad key: "0"–"9", "*" or "#".+ #[qinvokable]+ fn press(self: &PhoneCall, key: &QString);+ /// The call's volume up (true) or down.+ #[qinvokable]+ fn volume(self: &PhoneCall, up: bool);+ }+}++#[derive(Default)]+pub struct PhoneCallRust {+ device: QString,+ active: bool,+ caller: QString,+ number: QString,+ since: f64,+ can_end: bool,+ controls: bool,+ muted: bool,+ speaker: bool,+ held: bool,+ can_hold: bool,+ /// The call's ID on the phone, for its commands.+ call: Option<(DeviceId, String)>,+}++impl cxx_qt::Initialize for qobject::PhoneCall {+ fn initialize(self: Pin<&mut Self>) {+ super::subscribe(self.qt_thread(), Changes::CALLS | Changes::CAPABILITIES, Self::refresh);+ }+}++impl qobject::PhoneCall {+ pub fn set_device(mut self: Pin<&mut Self>, device: QString) {+ if self.rust().device == device {+ return;+ }+ self.as_mut().rust_mut().device = device;+ self.as_mut().device_changed();+ self.refresh();+ }++ fn refresh(mut self: Pin<&mut Self>) {+ let device = super::parse_device(&self.rust().device);+ let call = device.and_then(calls::active);+ let controls = call.as_ref().and_then(|c| c.controls);+ self.as_mut().rust_mut().call = device.zip(call.as_ref().map(|c| c.id.clone()));+ let (caller, number) = match &call {+ Some(call) => {+ let name = call.name.clone().filter(|n| !n.trim().is_empty());+ let number = call.number.clone().filter(|n| !n.trim().is_empty());+ match name {+ Some(name) => (name, number.unwrap_or_default()),+ None => (number.unwrap_or_else(|| "Unknown caller".into()), String::new()),+ }+ }+ None => Default::default(),+ };+ self.as_mut().set_caller(QString::from(&caller));+ self.as_mut().set_number(QString::from(&number));+ self.as_mut().set_since(call.as_ref().and_then(|c| c.since).unwrap_or(0) as f64);+ self.as_mut().set_can_end(device.is_some_and(calls::can_control));+ self.as_mut().set_controls(controls.is_some());+ let controls = controls.unwrap_or_default();+ self.as_mut().set_muted(controls.muted);+ self.as_mut().set_speaker(controls.speaker);+ self.as_mut().set_held(controls.held);+ self.as_mut().set_can_hold(controls.can_hold);+ self.as_mut().set_active(call.is_some());+ }++ fn send(&self, command: CallCommand) {+ if let Some((device, call)) = self.rust().call.clone() {+ calls::command(device, call, command);+ }+ }++ pub fn end(&self) {+ self.send(CallCommand::Decline);+ }++ pub fn set_mute(&self, on: bool) {+ self.send(CallCommand::Mute(on));+ }++ pub fn set_speaker_on(&self, on: bool) {+ self.send(CallCommand::Speaker(on));+ }++ pub fn set_hold(&self, on: bool) {+ self.send(CallCommand::Hold(on));+ }++ pub fn press(&self, key: &QString) {+ let key = String::from(key);+ if let [digit] = key.chars().collect::<Vec<_>>()[..]+ && (digit.is_ascii_digit() || digit == '*' || digit == '#')+ {+ self.send(CallCommand::Dtmf(digit));+ }+ }++ pub fn volume(&self, up: bool) {+ self.send(CallCommand::Volume(up));+ }+}diff --git a/desktop/app/src/bridge/mod.rs b/desktop/app/src/bridge/mod.rsindex 69a1dea..9f15bb0 100644--- a/desktop/app/src/bridge/mod.rs+++ b/desktop/app/src/bridge/mod.rs@@ -8,6 +8,8 @@#[allow(unsafe_code)]pub mod app;#[allow(unsafe_code)]+pub mod calls;+#[allow(unsafe_code)]pub mod devices;#[allow(unsafe_code)]pub mod history;diff --git a/desktop/app/src/calls.rs b/desktop/app/src/calls.rsindex bb0b26f..a59aaf1 100644--- a/desktop/app/src/calls.rs+++ b/desktop/app/src/calls.rs@@ -1,7 +1,9 @@// 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.+//! the phone), the call in progress (for Home's call card and a quiet+//! notification to mute or end it), and a notification for calls nobody+//! answered.use std::{collections::HashMap, path::PathBuf, sync::Mutex};@@ -10,12 +12,19 @@ use nectarlink_core::{CallCommand, CallState, DeviceId, Error, FeatureState, Linuse crate::{bridge::app::{describe, show_message},core_host,- win::toast::{self, CALL_ANSWER, CALL_DECLINE, Toast},+ state::Changes,+ win::toast::{self, CALL_ANSWER, CALL_DECLINE, CALL_END, Toast},};/// The toast "device" for calls; their key is `<device ID> <call ID>`.pub const TOAST_GROUP: &str = "calls";const ACTION_SILENCE: &str = "silence";+const ACTION_MUTE: &str = "mute";+const ACTION_UNMUTE: &str = "unmute";+const ACTION_SPEAKER: &str = "speaker";+const ACTION_EARPIECE: &str = "earpiece";+/// The in-call notification's key prefix (`active <device> <call>`).+const ACTIVE: &str = "active ";/// The ringing call shown per phone, to show it again (silenced) or take it/// away when it stops ringing.@@ -25,6 +34,32 @@ 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())}+/// The call in progress per phone (answered, or held).+static IN_PROGRESS: Mutex<Option<HashMap<DeviceId, CallState>>> = Mutex::new(None);++fn in_progress<T>(f: impl FnOnce(&mut HashMap<DeviceId, CallState>) -> T) -> T {+ f(IN_PROGRESS.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())+}++/// The call per phone whose in-call notification was shown.+static NOTIFIED: Mutex<Option<HashMap<DeviceId, String>>> = Mutex::new(None);++fn notified<T>(f: impl FnOnce(&mut HashMap<DeviceId, String>) -> T) -> T {+ f(NOTIFIED.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())+}++/// A phone's call in progress, if any.+pub fn active(device: DeviceId) -> Option<CallState> {+ in_progress(|c| c.get(&device).cloned())+}++/// Whether the PC can answer and end a phone's calls.+pub fn can_control(device: DeviceId) -> bool {+ core_host::host().hub.read(|s| {+ s.matrices.get(&device).and_then(|m| m.state("calls.control")) == Some(FeatureState::Available)+ })+}+fn key(device: DeviceId, call: &str) -> String {format!("{device} {call}")}@@ -32,13 +67,41 @@ fn key(device: DeviceId, call: &str) -> String {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),+ // A phone that's gone can't be answered (or hung up) from here.+ NodeEvent::LinkChanged { device, link: LinkState::Offline { .. } } => {+ stop_ringing(*device);+ finish(*device);+ }+ // A call can arrive before what the phone can do with it: once the+ // PC may end it, its notification shows.+ NodeEvent::Capabilities(matrix) if matrix.state("calls.control") == Some(FeatureState::Available) => {+ if let Some(call) = active(matrix.device)+ && notified(|n| n.get(&matrix.device) != Some(&call.id))+ {+ show_in_progress(matrix.device, &call);+ }+ }_ => {}}}fn changed(device: DeviceId, call: &CallState) {+ if call.state == "active" {+ match in_progress(|c| c.insert(device, call.clone())) {+ Some(previous) if previous.id == call.id => {}+ previous => {+ if let Some(previous) = previous {+ toast::remove(TOAST_GROUP, &format!("{ACTIVE}{}", key(device, &previous.id)));+ }+ if can_control(device) {+ show_in_progress(device, call);+ }+ }+ }+ core_host::host().hub.changed(Changes::CALLS);+ } else if call.state == "ended" || in_progress(|c| c.get(&device).is_some_and(|c| c.id == call.id)) {+ finish(device);+ }match call.state.as_str() {"ringing" if call.incoming => {if let Some(previous) = ringing(|r| r.insert(device, call.clone()))@@ -57,6 +120,15 @@ fn changed(device: DeviceId, call: &CallState) {}}+/// The call in progress is over (or out of reach).+fn finish(device: DeviceId) {+ notified(|n| n.remove(&device));+ if let Some(call) = in_progress(|c| c.remove(&device)) {+ toast::remove(TOAST_GROUP, &format!("{ACTIVE}{}", key(device, &call.id)));+ core_host::host().hub.changed(Changes::CALLS);+ }+}+fn stop_ringing(device: DeviceId) {if let Some(call) = ringing(|r| r.remove(&device)) {toast::remove(TOAST_GROUP, &key(device, &call.id));@@ -77,11 +149,8 @@ fn phone_name(device: DeviceId) -> String {}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 {+ if can_control(device) {actions.push((CALL_ANSWER.to_owned(), "Answer".to_owned()));actions.push((CALL_DECLINE.to_owned(), "Decline".to_owned()));if !silenced {@@ -111,6 +180,52 @@ fn show_ringing(device: DeviceId, call: &CallState, silenced: bool) {});}+/// A quiet notification for the call in progress: mute, speaker, end+/// (for a phone whose calls the PC controls).+fn show_in_progress(device: DeviceId, call: &CallState) {+ notified(|n| n.insert(device, call.id.clone()));+ let mut actions = Vec::new();+ if let Some(controls) = &call.controls {+ actions.push(if controls.muted {+ (ACTION_UNMUTE.to_owned(), "Unmute".to_owned())+ } else {+ (ACTION_MUTE.to_owned(), "Mute".to_owned())+ });+ actions.push(if controls.speaker {+ (ACTION_EARPIECE.to_owned(), "Earpiece".to_owned())+ } else {+ (ACTION_SPEAKER.to_owned(), "Speaker".to_owned())+ });+ }+ actions.push((CALL_END.to_owned(), "End".to_owned()));+ toast::show(Toast {+ device: TOAST_GROUP.into(),+ key: format!("{ACTIVE}{}", key(device, &call.id)),+ title: format!("On a call with {}", caller(call)),+ body: format!("On {}", phone_name(device)),+ attribution: "Nectarlink".into(),+ icon: None,+ image: None,+ actions,+ reply: None,+ silent: true,+ progress: None,+ call: false,+ });+}++/// Asks a phone to do something with its call; problems are shown.+pub fn command(device: DeviceId, call: String, command: CallCommand) {+ let Some(node) = core_host::node() else { return };+ core_host::spawn(async move {+ match node.call_command(device, call, command).await {+ Ok(()) => {}+ Err(Error::NotFound) => show_message("That call is over."),+ Err(e) => show_message(describe(&e)),+ }+ });+}+fn show_missed(device: DeviceId, call: &CallState) {toast::show(Toast {device: TOAST_GROUP.into(),@@ -146,14 +261,43 @@ pub fn on_toast(key: &str, action: &str) {if key.starts_with("missed ") {return;}+ let (key, in_call) = match key.strip_prefix(ACTIVE) {+ Some(key) => (key, true),+ None => (key, false),+ };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,+ CALL_DECLINE | CALL_END => CallCommand::Decline,ACTION_SILENCE => CallCommand::Silence,+ ACTION_MUTE => CallCommand::Mute(true),+ ACTION_UNMUTE => CallCommand::Mute(false),+ ACTION_SPEAKER => CallCommand::Speaker(true),+ ACTION_EARPIECE => CallCommand::Speaker(false),_ => return,};+ if in_call {+ // A button took the notification away: it comes back (quietly) once+ // the phone has done it, with the new state, unless the call ended.+ 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 {+ Ok(()) if command == CallCommand::Decline => {}+ Ok(()) => {+ // The phone's new state comes as its own event, right after.+ tokio::time::sleep(std::time::Duration::from_millis(400)).await;+ if let Some(active) = active(device).filter(|c| c.id == call) {+ show_in_progress(device, &active);+ }+ }+ Err(Error::NotFound) => show_message("That call is over."),+ Err(e) => show_message(describe(&e)),+ }+ });+ return;+ }let Some(node) = core_host::node() else { return };let call = call.to_owned();core_host::spawn(async move {@@ -184,6 +328,8 @@ mod tests {name: name.map(Into::into),photo: None,missed: false,+ since: None,+ controls: None,}}diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rsindex a16615b..ea44727 100644--- a/desktop/app/src/state.rs+++ b/desktop/app/src/state.rs@@ -40,6 +40,8 @@ impl Changes {pub const MESSAGES: Changes = Changes(1 << 12);/// Mirroring a phone's screen (kept by crate::mirror).pub const MIRROR: Changes = Changes(1 << 13);+ /// A call in progress on a phone (kept by crate::calls).+ pub const CALLS: Changes = Changes(1 << 14);pub fn is_empty(self) -> bool {self.0 == 0diff --git a/desktop/app/src/win/toast.rs b/desktop/app/src/win/toast.rsindex 0e30580..96a9fa8 100644--- a/desktop/app/src/win/toast.rs+++ b/desktop/app/src/win/toast.rs@@ -69,6 +69,8 @@ pub struct Toast {pub actions: Vec<(String, String)>,/// `(action id, placeholder)` for an inline reply.pub reply: Option<(String, String)>,+ /// No sound and no pop-up (straight to the notification center); a+ /// call's notification (ringing, or with End) still pops up, quietly.pub silent: bool,/// A progress bar, updated in place with [`update_progress`].pub progress: Option<Progress>,@@ -285,7 +287,8 @@ fn show_now(notifier: &ToastNotifier, toast: Toast, handler: &'static Handler) -notification.SetTag(&HSTRING::from(tag(&toast.key)))?;notification.SetGroup(&HSTRING::from(group(&toast.device)))?;// Silent on the phone: straight to the notification center, no pop-up.- notification.SetSuppressPopup(toast.silent)?;+ // A call's stays in sight: it's about something happening now.+ notification.SetSuppressPopup(toast.silent && !toast.call && !ends_call(&toast))?;if let Some(progress) = &toast.progress {notification.SetData(&progress_data(progress)?)?;}@@ -385,11 +388,20 @@ fn escape(text: &str) -> String {/// 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";+/// On any toast, the action shown as End (red): hanging up a call.+pub const CALL_END: &str = "end";++/// Whether it's about a call in progress (it has an End button).+fn ends_call(toast: &Toast) -> bool {+ toast.actions.iter().any(|(id, _)| id == CALL_END)+}/// The toast's XML (Windows toast schema).fn toast_xml(toast: &Toast) -> String {let mut xml = String::from(if toast.call {r#"<toast launch="open" scenario="incomingCall" useButtonStyle="true"><visual><binding template="ToastGeneric">"#+ } else if ends_call(toast) {+ r#"<toast launch="open" useButtonStyle="true"><visual><binding template="ToastGeneric">"#} else {r#"<toast launch="open"><visual><binding template="ToastGeneric">"#});@@ -429,10 +441,10 @@ 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) {- // On a call: Answer green, Decline red.+ // On a call: Answer green, Decline and End red.let style = match (toast.call, id.as_str()) {(true, CALL_ANSWER) => r#" hint-buttonStyle="Success""#,- (true, CALL_DECLINE) => r#" hint-buttonStyle="Critical""#,+ (true, CALL_DECLINE) | (_, CALL_END) => r#" hint-buttonStyle="Critical""#,_ => "",};xml.push_str(&format!(@@ -502,6 +514,17 @@ mod tests {XmlDocument::new().unwrap().LoadXml(&HSTRING::from(xml)).expect("well-formed XML");}+ #[test]+ fn calls_in_progress_end_in_red_quietly() {+ let actions = vec![("mute".into(), "Mute".into()), (CALL_END.into(), "End".into())];+ let xml = toast_xml(&Toast { silent: true, reply: None, actions, ..toast() });+ assert!(xml.starts_with(r#"<toast launch="open" useButtonStyle="true">"#), "{xml}");+ assert!(xml.contains(r#"arguments="a:end" hint-buttonStyle="Critical""#), "{xml}");+ assert!(xml.contains(r#"arguments="a:mute"/>"#), "{xml}");+ assert!(!xml.contains("incomingCall"), "{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/PLAN.md b/docs/PLAN.mdindex 8367218..b26e1de 100644--- a/docs/PLAN.md+++ b/docs/PLAN.md@@ -138,10 +138,15 @@ Power: 🟢 Basic · 🔵 Assist · 🟣 Elevated (see §4.6).| Feature | Tier ||---|---|| Incoming call alert on PC with caller photo; answer / decline / silence (audio stays on phone) | P0 🟢 |+| Call in progress on PC: timer, hang up, volume; with Elevated (Android 12+), mute, speaker, hold and keypad through a calling-companion `InCallService` | P0 🟢 || Call log, dialer, call from contacts | P1 🟢 || **Call audio on PC via Bluetooth HFP** (PC mic/speakers) | P1 (after spike) || Auto-pause PC media during calls | P1 |+Not planned: **recording calls.** Android keeps call audio (`VOICE_CALL`+capture) to privileged apps, so a third-party app can't record calls on+current Android. Talking through the PC comes with the HFP item above.+### 3.5 Clipboard| Feature | Tier ||---|---|@@ -398,7 +403,7 @@ Everything ships inside the single Nectarlink APK. "Elevated" is **not a separat| Stay alive | FGS `connectedDevice`, CompanionDeviceManager + presence observing, battery exemption || Notifications | `NotificationListenerService` (+ RemoteInput replies, actions, MessagingStyle parsing) || SMS/MMS, call log, contacts | Telephony & Contacts providers |-| Calls | `TelephonyCallback`, `TelecomManager.acceptRingingCall/endCall` |+| Calls | `TelephonyCallback`, `TelecomManager.acceptRingingCall/endCall`; in-call controls through an `InCallService` bound as a calling companion (`MANAGE_ONGOING_CALLS`, granted by Elevated) || Media | `MediaSessionManager.getActiveSessions`, our own `MediaSession` for PC media || Voice recorder | `AudioRecord` / MediaCodec (Opus/AAC), with format conversion in the Rust core on PC for MP3/WAV/FLAC || Voice typing | `SpeechRecognizer` (on-device where available) |diff --git a/docs/protocol/calls.md b/docs/protocol/calls.mdindex 6dd1e06..bad7b14 100644--- a/docs/protocol/calls.md+++ b/docs/protocol/calls.md@@ -4,15 +4,18 @@> 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.+and when it ends. A PC can answer, decline or silence a ringing call, and+hang up, mute, switch to the speaker, hold, press keypad keys and change+the volume of the call in progress. 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.control` | phone | Answers, declines, silences and hangs up calls, and changes their volume, when a PC asks |+| `call.incall` | phone | Also mutes, switches to the speaker, holds and presses keys on the call in progress, and reports those `controls` || `call.show` | PC | Shows calls |A phone reports calls only to PCs that offer `call.show`, and only while@@ -32,16 +35,33 @@ t = "call.state" b = {? 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)+ ? since: int, // With "active": when it was answered, in Unix milliseconds+ ? controls: { // With "active", from a phone offering call.incall+ ? muted: bool, // The phone's microphone is muted+ ? speaker: bool, // The sound is on the speaker+ ? held: bool, // The call is on hold+ ? can_hold: bool, // The call can be held+ },+}+t = "call.action" id = n b = {+ id: text,+ action: "answer" | "decline" | "silence"+ | "mute" | "unmute" | "speaker" | "earpiece" | "hold" | "unhold"+ | "dtmf" | "volume_up" | "volume_down",+ ? digit: text, // With "dtmf": one of 0–9, * and #}-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.+such as the number), when it's answered, whenever its `controls` change,+and when it ends. Not answered. A PC that connects during a call gets its+latest `call.state` right away.++`controls` is there only while the phone can change them: a PC shows+mute, speaker, hold and the keypad only then.A call that was declined, on the phone or from a PC, ends without`missed`.@@ -51,10 +71,36 @@ A call that was declined, on the phone or from a PC, ends without- `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`.+- `volume_up`, `volume_down`: the active call's volume (`call.control`).+- `mute`, `unmute`, `speaker`, `earpiece`, `hold`, `unhold`: as named, on+ the active call (`call.incall`). The new state comes back in+ `call.state`.+- `dtmf`: plays the keypad tone `digit` on the active call (`call.incall`).++Errors: `NOT_FOUND` when `id` isn't the call in progress, or the action+doesn't fit its state (`answer` and `silence` need it ringing; the others,+except `decline`, need it active); `DENIED` when calls are off for the PC;+`UNSUPPORTED` for an unknown action, a `dtmf` without a valid `digit`, or+when the phone doesn't offer the capability the action needs.++### 2.3 On Android++`call.control` needs the phone permission and the permission to answer+calls. `call.incall` needs Android 12 or later and the+`MANAGE_ONGOING_CALLS` app-op, which lets Telecom bind Nectarlink's+in-call service as a calling companion without it being the phone app.+Apps can't grant that app-op to themselves; Nectarlink's Elevated mode+(Wireless debugging) grants it through the shell when it starts.++Not in this service:++- **Recording calls.** Android doesn't let apps other than the phone's+ own record call audio (capturing the voice call stream needs a+ privileged permission), so Nectarlink doesn't offer it.+- **Talking through the PC.** Carrying the call's audio to the PC's+ microphone and speakers is planned as a Bluetooth hands-free (HFP)+ link from the PC to the phone, as for a headset; it isn't part of this+ service.## 3. Privacydiff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.mdindex 5132670..1867871 100644--- a/docs/protocol/capabilities.md+++ b/docs/protocol/capabilities.md@@ -38,6 +38,7 @@ capability is missing.| `sms.send` | Sends texts when a PC asks ([messages](sms.md)) | SMS 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 |+| `call.incall` | Mutes, holds and presses keys on the call in progress ([calls](calls.md)) | Elevated, Android 12+ || `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 |