Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
feat: pick the SIM a call from the PC goes out on
Beeca91c3abe446
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.ktindex 0e598fc..22479b0 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@@ -19,7 +19,10 @@ import android.os.Handlerimport android.os.Looperimport android.provider.CallLogimport android.provider.ContactsContract+import android.telecom.PhoneAccount+import android.telecom.PhoneAccountHandleimport android.telecom.TelecomManager+import android.telephony.SubscriptionManagerimport android.telephony.TelephonyManagerimport android.util.Logimport androidx.core.content.ContextCompat@@ -29,6 +32,7 @@ import app.nectarlink.core.Callimport app.nectarlink.core.CallCommandimport app.nectarlink.core.CallLogEntryimport app.nectarlink.core.CallPhase+import app.nectarlink.core.CallSimimport java.io.ByteArrayOutputStreamimport java.util.concurrent.Executors@@ -413,7 +417,64 @@ internal class PhoneCalls(* number pre-filled (`Intent.ACTION_DIAL`).*/@SuppressLint("MissingPermission")- fun dial(number: String): Boolean {+ fun dial(number: String): Boolean = dial(number, null)++ /**+ * The SIMs (and calling apps) this phone calls with (#112), so a PC can+ * pick one rather than leave Android asking on the phone. Each is named+ * by its slot and carrier where Android says ("SIM 1 · Airtel").+ */+ @SuppressLint("MissingPermission")+ fun sims(): List<CallSim> {+ if (!canListSims(context)) return emptyList()+ return runCatching {+ val tm = context.getSystemService(TelecomManager::class.java) ?: return emptyList()+ val default = tm.getDefaultOutgoingPhoneAccount(PhoneAccount.SCHEME_TEL)+ tm.callCapablePhoneAccounts.mapNotNull { handle ->+ val account = tm.getPhoneAccount(handle) ?: return@mapNotNull null+ CallSim(id = handle.id, label = simLabel(handle, account), isDefault = handle == default)+ }+ }.getOrElse {+ Log.w(TAG, "can't list the SIMs", it)+ emptyList()+ }+ }++ /** Places a call to [number] on the SIM [sim] (an id from [sims]), or on the default when it's gone. */+ @SuppressLint("MissingPermission")+ fun dialOn(number: String, sim: String): Boolean {+ val handle = if (canListSims(context)) {+ runCatching {+ context.getSystemService(TelecomManager::class.java)?.callCapablePhoneAccounts?.firstOrNull { it.id == sim }+ }.getOrNull()+ } else {+ null+ }+ return dial(number, handle)+ }++ @SuppressLint("MissingPermission")+ private fun simLabel(handle: PhoneAccountHandle, account: PhoneAccount): String {+ val carrier = account.label?.toString()?.trim().orEmpty()+ val slot = runCatching {+ val subId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ context.getSystemService(TelephonyManager::class.java)?.getSubscriptionId(handle)+ } else {+ handle.id.toIntOrNull()+ } ?: return@runCatching null+ context.getSystemService(SubscriptionManager::class.java)+ ?.getActiveSubscriptionInfo(subId)?.simSlotIndex?.takeIf { it >= 0 }?.plus(1)+ }.getOrNull()+ return when {+ slot != null && carrier.isNotEmpty() -> "SIM $slot · $carrier"+ slot != null -> "SIM $slot"+ carrier.isNotEmpty() -> carrier+ else -> handle.id+ }.take(MAX_SIM_LABEL)+ }++ @SuppressLint("MissingPermission")+ private fun dial(number: String, account: PhoneAccountHandle?): Boolean {val trimmed = number.trim()if (trimmed.isEmpty()) return falselastDialed = trimmed to System.currentTimeMillis()@@ -426,14 +487,18 @@ internal class PhoneCalls(val tm = context.getSystemService(TelecomManager::class.java)if (tm != null) {try {- tm.placeCall(uri, android.os.Bundle.EMPTY)+ val extras = android.os.Bundle()+ if (account != null) extras.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, account)+ tm.placeCall(uri, extras)return@runCatching true} catch (_: SecurityException) {// Fall back to the intents below if Telecom refused.}}try {- context.startActivity(Intent(Intent.ACTION_CALL, uri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+ val call = Intent(Intent.ACTION_CALL, uri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ if (account != null) call.putExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, account)+ context.startActivity(call)return@runCatching true} catch (_: SecurityException) {// Fall back to the dialer below if the OS blocked direct calling.@@ -497,6 +562,8 @@ internal class PhoneCalls(private const val PREFS = "phone_calls"private const val MUTED_RINGER = "muted_ringer"private const val TAG = "PhoneCalls"+ /** The protocol's limit for a label (`calls::MAX_TEXT_BYTES`), in characters to be safe. */+ private const val MAX_SIM_LABEL = 64@Volatile private var instance: PhoneCalls? = null@@ -542,6 +609,12 @@ internal class PhoneCalls(context.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) &&(granted(context, Manifest.permission.CALL_PHONE) || canFollow(context))+ /** Whether it can list its SIMs and call on the one a PC picks (`call.sims`). */+ fun canListSims(context: Context) =+ context.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) &&+ granted(context, Manifest.permission.CALL_PHONE) &&+ granted(context, Manifest.permission.READ_PHONE_STATE)+/** 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.ktindex 67e0fca..f922df7 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@@ -1886,6 +1886,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener(if (PhoneCalls.canControl(context) && CallCompanion.allowed(context)) listOf("call.incall") else emptyList()) +(if (PhoneCalls.canReadLog(context)) listOf("call.log") else emptyList()) +(if (PhoneCalls.canDial(context)) listOf("call.dial") else emptyList()) ++ (if (PhoneCalls.canListSims(context)) listOf("call.sims") else emptyList()) +(if (PhoneContacts.canRead(context)) listOf("contacts.read") else emptyList()) +(if (PhoneSms.canRead(context)) listOf("sms.read") else emptyList()) +(if (PhoneSms.canSend(context)) listOf("sms.send") else emptyList()) +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.ktindex d6b6c91..eaa2b32 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@@ -134,6 +134,10 @@ internal class PhonePlatform(override fun callDial(number: String): Boolean = calls().dial(number)+ override fun callSims(): List<app.nectarlink.core.CallSim> = calls().sims()++ override fun callDialOn(number: String, sim: String): Boolean = calls().dialOn(number, sim)+override fun contacts(query: String?, offset: UInt, limit: UInt): List<Contact> =contacts().list(query, offset.toInt(), limit.toInt())diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex dec4949..4a4963d 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -3909,7 +3909,7 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {wait_until_online(node, id).await?;match number {Some(number) => {- node.call_dial(id, number.clone()).await.context("couldn't start the call")?;+ node.call_dial(id, number.clone(), None).await.context("couldn't start the call")?;println!("Calling {number}…");}None => {diff --git a/core/nectarlink-core/src/calls.rs b/core/nectarlink-core/src/calls.rsindex b99f031..5a40ef3 100644--- a/core/nectarlink-core/src/calls.rs+++ b/core/nectarlink-core/src/calls.rs@@ -11,7 +11,7 @@ use std::{use nectarlink_protocol::{Envelope, ErrorCode,messages::{- CallAction, CallDial, CallLog, CallLogChanged, CallLogEntry, CallLogGet, CallState, calls,+ CallAction, CallDial, CallLog, CallLogChanged, CallLogEntry, CallLogGet, CallSims, CallState, calls,is_dtmf_digit, types,},};@@ -210,11 +210,18 @@ pub(crate) async fn log(Ok(entries)}-pub(crate) async fn dial(shared: &Shared, session: &Session, number: String) -> Result<()> {+pub(crate) async fn dial(+ shared: &Shared,+ session: &Session,+ number: String,+ sim: Option<String>,+) -> Result<()> {if !shared.toggle_on(&session.peer, TOGGLE) {return Err(Error::Denied);}- let dial = CallDial { number: number.trim().to_owned() };+ // A phone from before `call.sims` dials on its own default either way.+ let sim = sim.filter(|_| peer_offers(shared, session, calls::SIMS));+ let dial = CallDial { number: number.trim().to_owned(), sim };if !dial.is_valid() {return Err(if dial.number.len() > calls::MAX_TEXT_BYTES {Error::TooLarge@@ -227,6 +234,30 @@ pub(crate) async fn dial(shared: &Shared, session: &Session, number: String) ->Ok(())}+/// Whether the device on `session` said it offers `cap` (in its last hello+/// or capability update).+fn peer_offers(shared: &Shared, session: &Session, cap: &str) -> bool {+ shared.store.get_peer(&session.peer).ok().flatten().is_some_and(|record| record.caps.contains(cap))+}++/// The phone's SIMs, to pick one for [`dial`]; none from a phone that+/// doesn't list them.+pub(crate) async fn sims(shared: &Shared, session: &Session) -> Result<CallSims> {+ if !shared.toggle_on(&session.peer, TOGGLE) {+ return Err(Error::Denied);+ }+ if !peer_offers(shared, session, calls::SIMS) {+ return Ok(CallSims::default());+ }+ let env = Envelope::new(types::CALL_SIMS, &CallSims::default())?;+ let sims: CallSims =+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect_body(types::CALL_SIMS)?;+ if !sims.is_valid() {+ return Err(Error::Protocol("invalid SIM list".into()));+ }+ Ok(sims)+}+/// 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;@@ -280,7 +311,7 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Esession.send(reply.reply_to(env.id)).await?;Ok(true)}- types::CALL_LOG | types::CALL_DIAL => {+ types::CALL_LOG | types::CALL_DIAL | types::CALL_SIMS => {// Reading the call log or starting a call takes a moment: run off the session's loop,// while keeping `call.state` and `call.action` in order on the stream.let (shared, session, env) = (shared.clone(), session.clone(), env.clone());@@ -304,6 +335,21 @@ async fn answer_log_or_dial(shared: &Arc<Shared>, session: &Session, env: &Envellet offers = |cap: &str| shared.we_offer(cap);let platform = shared.platform.clone();let result = match env.t.as_str() {+ types::CALL_SIMS => {+ if !offers(calls::SIMS) {+ return Ok(Envelope::error(ErrorCode::Unsupported, "this phone doesn't list its SIMs"));+ }+ tokio::task::spawn_blocking(move || {+ let mut sims = platform.call_sims()?;+ sims.sims.truncate(calls::MAX_SIMS);+ if !sims.is_valid() {+ return Err("the phone's SIM list didn't check out".to_owned());+ }+ Envelope::new(types::CALL_SIMS, &sims).map_err(|e| e.to_string())+ })+ .await+ .unwrap_or_else(|e| Err(e.to_string()))+ }types::CALL_LOG => {if !offers(calls::LOG) {return Ok(Envelope::error(ErrorCode::Unsupported, "this phone doesn't share recent calls"));@@ -331,8 +377,13 @@ async fn answer_log_or_dial(shared: &Arc<Shared>, session: &Session, env: &Envelreturn Ok(Envelope::error(ErrorCode::BadMessage, "invalid number"));}let number = dial.number.trim().to_owned();+ let sim = dial.sim.filter(|_| offers(calls::SIMS));tokio::task::spawn_blocking(move || {- platform.call_dial(&number).map(|()| Envelope::empty(types::OK))+ match sim.as_deref() {+ Some(sim) => platform.call_dial_on(&number, sim),+ None => platform.call_dial(&number),+ }+ .map(|()| Envelope::empty(types::OK))}).await.unwrap_or_else(|e| Err(e.to_string()))diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rsindex 4d483ac..ec44327 100644--- a/core/nectarlink-core/src/config.rs+++ b/core/nectarlink-core/src/config.rs@@ -382,6 +382,18 @@ pub trait Platform: Send + Sync + 'static {Err("this device doesn't place calls".into())}+ /// The SIMs (and calling apps) this phone places calls with, and the one+ /// it uses without asking (a PC asked; offered as `call.sims`).+ fn call_sims(&self) -> Result<nectarlink_protocol::messages::CallSims, String> {+ Ok(Default::default())+ }++ /// Like [`call_dial`](Self::call_dial), on the SIM `sim` (an id from+ /// [`call_sims`](Self::call_sims)).+ fn call_dial_on(&self, number: &str, _sim: &str) -> Result<(), String> {+ self.call_dial(number)+ }+/// This phone's contacts matching `query` (or all with phone numbers/// when `None`), favorites first then alphabetical, skipping `offset`/// (a PC asked).diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsindex 2205160..5371d38 100644--- a/core/nectarlink-core/src/lib.rs+++ b/core/nectarlink-core/src/lib.rs@@ -83,7 +83,7 @@ pub use nectarlink_protocol::messages::clip::{pub use nectarlink_protocol::{DeviceId, PacketKind,messages::{- AudioOutputDevice, Battery, CLIP_MAX_BYTES, CallControls, CallLogEntry, CallState,+ AudioOutputDevice, Battery, CLIP_MAX_BYTES, CallControls, CallLogEntry, CallSim, CallSims, CallState,CameraCaptureCancel, CameraCaptureMode, CameraCaptureOk, CameraCaptureRequest,CameraCaptureResultMeta, Contact, ContactNumber, DeviceInfo, DeviceKind, LivePoint, LiveSegment,MediaPlayer, MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorPower, MirrorResize, MirrorStart,@@ -96,7 +96,7 @@ pub use nectarlink_protocol::{WebcamConfig, WebcamStart,calls::{CONTROL as CALLS_CONTROL, DIAL as CALLS_DIAL, IN_CALL as CALLS_IN_CALL, LOG as CALLS_LOG,- SHOW as CALLS_SHOW, STATE as CALLS_STATE,+ SHOW as CALLS_SHOW, SIMS as CALLS_SIMS, STATE as CALLS_STATE,},contacts::{READ as CONTACTS_READ, SHOW as CONTACTS_SHOW},continuity_camera::{diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rsindex 1dc611a..f84eac7 100644--- a/core/nectarlink-core/src/node.rs+++ b/core/nectarlink-core/src/node.rs@@ -2991,10 +2991,18 @@ impl Node {}/// Asks a paired phone to place a call to `number` (or open the dialer- /// with it filled in).- pub async fn call_dial(&self, peer: DeviceId, number: String) -> Result<()> {+ /// with it filled in), on the SIM `sim` (an id from [`call_sims`](Self::call_sims))+ /// when given.+ pub async fn call_dial(&self, peer: DeviceId, number: String, sim: Option<String>) -> Result<()> {let session = self.connected(&peer)?;- crate::calls::dial(&self.shared, &session, number).await+ crate::calls::dial(&self.shared, &session, number, sim).await+ }++ /// A paired phone's SIMs, to choose which one [`call_dial`](Self::call_dial)+ /// uses; empty for a phone that doesn't list them.+ pub async fn call_sims(&self, peer: DeviceId) -> Result<crate::CallSims> {+ let session = self.connected(&peer)?;+ crate::calls::sims(&self.shared, &session).await}// ---- Contacts (docs/protocol/contacts.md) ----diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex 78d0b9c..9504574 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -319,6 +319,19 @@ impl Platform for RecordingPlatform {self.dialed.lock().unwrap().push(number.to_owned());Ok(())}+ fn call_sims(&self) -> Result<nectarlink_core::CallSims, String> {+ Ok(nectarlink_core::CallSims {+ sims: vec![+ nectarlink_core::CallSim { id: "1".into(), label: "SIM 1 · Airtel".into() },+ nectarlink_core::CallSim { id: "2".into(), label: "SIM 2 · Jio".into() },+ ],+ default: None,+ })+ }+ fn call_dial_on(&self, number: &str, sim: &str) -> Result<(), String> {+ self.dialed.lock().unwrap().push(format!("{number} on {sim}"));+ Ok(())+ }fn contacts(&self,query: Option<&str>,@@ -2461,7 +2474,7 @@ async fn call_log_and_dial_work_and_respect_permissions_and_toggles() {.await;// Without `call.dial` on the phone, dialing from the PC is refused as unsupported.- assert!(matches!(pc.node.call_dial(phone_id, "+15550100".into()).await, Err(Error::Unsupported)));+ assert!(matches!(pc.node.call_dial(phone_id, "+15550100".into(), None).await, Err(Error::Unsupported)));phone.node@@ -2484,13 +2497,50 @@ async fn call_log_and_dial_work_and_respect_permissions_and_toggles() {}).await;- with_timeout("dial", pc.node.call_dial(phone_id, "+15550100".into())).await.unwrap();+ with_timeout("dial", pc.node.call_dial(phone_id, "+15550100".into(), None)).await.unwrap();assert_eq!(*phone.platform.dialed.lock().unwrap(), ["+15550100"]);+ // A phone that doesn't list its SIMs has none to pick, and a SIM the PC+ // names anyway isn't sent: it dials on its own default.+ assert_eq!(with_timeout("no sims", pc.node.call_sims(phone_id)).await.unwrap(), Default::default());+ with_timeout("dial on a sim", pc.node.call_dial(phone_id, "+15550101".into(), Some("2".into())))+ .await+ .unwrap();+ assert_eq!(phone.platform.dialed.lock().unwrap().last().map(String::as_str), Some("+15550101"));++ // With `call.sims`, the PC sees the SIMs and the phone dials on the one picked.+ phone+ .node+ .update_power(+ PowerLevel::NotApplicable,+ vec![+ "media.control".into(),+ nectarlink_core::CALLS_LOG.into(),+ nectarlink_core::CALLS_DIAL.into(),+ nectarlink_core::CALLS_SIMS.into(),+ ],+ )+ .await;+ let sims = loop {+ let sims = with_timeout("sims", pc.node.call_sims(phone_id)).await.unwrap();+ if !sims.sims.is_empty() {+ break sims;+ }+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;+ };+ assert_eq!(+ sims.sims.iter().map(|s| s.label.as_str()).collect::<Vec<_>>(),+ ["SIM 1 · Airtel", "SIM 2 · Jio"]+ );+ with_timeout("dial on sim 2", pc.node.call_dial(phone_id, "+15550102".into(), Some("2".into())))+ .await+ .unwrap();+ assert_eq!(phone.platform.dialed.lock().unwrap().last().map(String::as_str), Some("+15550102 on 2"));+// Turning `calls` off for this PC blocks both call log and dialing.phone.node.set_device_toggle(pc_id, "calls", false).unwrap();assert!(matches!(pc.node.call_log(phone_id, None, 3).await, Err(Error::Denied)));- assert!(matches!(pc.node.call_dial(phone_id, "+15550100".into()).await, Err(Error::Denied)));+ assert!(matches!(pc.node.call_dial(phone_id, "+15550100".into(), None).await, Err(Error::Denied)));}#[tokio::test(flavor = "multi_thread")]diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex 6b109da..b3be0d8 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -1305,6 +1305,18 @@ macro_rules! private_debug {}private_debug!(SmsThread, SmsMessage, SmsPartData, SmsAttachment, CallLogEntry, ContactNumber, Contact);+/// One SIM (or calling app) this phone places calls with+/// (docs/protocol/calls.md, `call.sims`).+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]+pub struct CallSim {+ /// Stays the same while the SIM is in: what `call_dial_on` gets back.+ pub id: String,+ /// What Android shows for it, such as "SIM 1 · Airtel".+ pub label: String,+ /// Whether the phone calls with it without asking.+ pub is_default: bool,+}+/// One call in this phone's call history (docs/protocol/calls.md).#[derive(Clone, PartialEq, Eq, uniffi::Record)]pub struct CallLogEntry {@@ -2672,6 +2684,10 @@ pub trait Platform: Send + Sync {/// A PC asked to call `number` (or open the dialer with it filled in)./// False if the phone couldn't.fn call_dial(&self, number: String) -> bool;+ /// A PC asked which SIMs this phone calls with.+ fn call_sims(&self) -> Vec<CallSim>;+ /// Like `call_dial`, on the SIM `sim` (an id from `call_sims`).+ fn call_dial_on(&self, number: String, sim: String) -> bool;/// A PC asked for contacts matching `query` (or all with phone numbers/// when null), favorites first then alphabetical, skipping `offset`.fn contacts(&self, query: Option<String>, offset: u32, limit: u32) -> Vec<Contact>;@@ -3057,6 +3073,21 @@ impl core::Platform for PlatformAdapter {fn call_dial(&self, number: &str) -> Result<(), String> {if self.0.call_dial(number.to_owned()) { Ok(()) } else { Err("the phone couldn't".into()) }}+ fn call_sims(&self) -> Result<core::CallSims, String> {+ let sims = self.0.call_sims();+ let default = sims.iter().find(|s| s.is_default).map(|s| s.id.clone());+ Ok(core::CallSims {+ sims: sims.into_iter().map(|s| core::CallSim { id: s.id, label: s.label }).collect(),+ default,+ })+ }+ fn call_dial_on(&self, number: &str, sim: &str) -> Result<(), String> {+ if self.0.call_dial_on(number.to_owned(), sim.to_owned()) {+ Ok(())+ } else {+ Err("the phone couldn't".into())+ }+ }fn contacts(&self, query: Option<&str>, offset: u32, limit: u32) -> Result<Vec<core::Contact>, String> {Ok(self.0diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex 2eda5f7..7a752bf 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -60,6 +60,7 @@ pub mod types {pub const CALL_LOG: &str = "call.log";pub const CALL_LOG_CHANGED: &str = "call.log.changed";pub const CALL_DIAL: &str = "call.dial";+ pub const CALL_SIMS: &str = "call.sims";pub const CONTACTS_LIST: &str = "contacts.list";pub const CONTACTS_CHANGED: &str = "contacts.changed";pub const SMS_THREADS: &str = "sms.threads";@@ -2221,6 +2222,11 @@ pub mod calls {pub const LOG: &str = "call.log";/// Offered by phones that place calls (or open the dialer) when a PC asks.pub const DIAL: &str = "call.dial";+ /// Offered by phones that list their SIMs (`call.sims`) and dial on the+ /// one a PC picks (`call.dial`'s `sim`).+ pub const SIMS: &str = "call.sims";+ /// Most SIMs (phone accounts that place calls) in one answer.+ pub const MAX_SIMS: usize = 8;/// A caller's photo: a JPEG of at most this many bytes.pub const MAX_PHOTO_BYTES: usize = 64 * 1024;/// A contact's photo on a call log entry: a JPEG of at most this many bytes.@@ -2394,16 +2400,20 @@ pub struct CallLog {#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct CallLogChanged {}-/// Body of `call.dial`: ask the phone to call `number`.+/// Body of `call.dial`: ask the phone to call `number`, on the SIM `sim`+/// (an `id` from `call.sims`) when given. Phones from before `sim` ignore it+/// and use their own default.#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct CallDial {pub number: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub sim: Option<String>,}/// Never prints the number (protocol v0 §11).impl std::fmt::Debug for CallDial {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.debug_struct("CallDial").field("bytes", &self.number.len()).finish()+ f.debug_struct("CallDial").field("bytes", &self.number.len()).field("sim", &self.sim).finish()}}@@ -2412,6 +2422,40 @@ impl CallDial {!self.number.trim().is_empty()&& self.number.len() <= calls::MAX_TEXT_BYTES&& !self.number.chars().any(char::is_control)+ && self.sim.as_deref().is_none_or(is_valid_sim_id)+ }+}++fn is_valid_sim_id(id: &str) -> bool {+ !id.is_empty() && id.len() <= calls::MAX_ID_BYTES && !id.chars().any(char::is_control)+}++/// One way the phone places calls (`call.sims`): a SIM, or a calling app+/// such as a SIP account. `label` is what Android shows ("SIM 1 · Airtel").+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct CallSim {+ pub id: String,+ pub label: String,+}++/// Answer to `call.sims` (an empty body asks): the phone's SIMs, and the+/// one it uses without asking, if it has one.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct CallSims {+ pub sims: Vec<CallSim>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub default: Option<String>,+}++impl CallSims {+ pub fn is_valid(&self) -> bool {+ self.sims.len() <= calls::MAX_SIMS+ && self.sims.iter().all(|s| {+ is_valid_sim_id(&s.id)+ && s.label.len() <= calls::MAX_TEXT_BYTES+ && !s.label.chars().any(char::is_control)+ })+ && self.default.as_deref().is_none_or(|d| self.sims.iter().any(|s| s.id == d))}}@@ -4328,9 +4372,9 @@ mod tests {assert!(PhotoGet { id: String::new(), ids: Vec::new() }.requested_ids().is_empty());// Dialled numbers: pauses and waits are fine, control characters aren't.- assert!(CallDial { number: "+1 555 0100,,23#".into() }.is_valid());- assert!(CallDial { number: "555;1".into() }.is_valid());- assert!(!CallDial { number: "555\n0100".into() }.is_valid());+ assert!(CallDial { number: "+1 555 0100,,23#".into(), sim: None }.is_valid());+ assert!(CallDial { number: "555;1".into(), sim: None }.is_valid());+ assert!(!CallDial { number: "555\n0100".into(), sim: None }.is_valid());// `plugged` keeps only the documented values.let battery = |plugged: &str| Battery {@@ -4956,11 +5000,31 @@ mod tests {#[test]fn call_log_dial_and_contacts_round_trip_and_hide_private_fields() {- let dial = CallDial { number: "+1 555 0100".into() };+ let dial = CallDial { number: "+1 555 0100".into(), sim: None };assert!(dial.is_valid());assert!(!format!("{dial:?}").contains("555"));- assert!(!CallDial { number: " ".into() }.is_valid());- assert!(!CallDial { number: "1".repeat(calls::MAX_TEXT_BYTES + 1) }.is_valid());+ assert!(!CallDial { number: " ".into(), sim: None }.is_valid());+ assert!(!CallDial { number: "1".repeat(calls::MAX_TEXT_BYTES + 1), sim: None }.is_valid());+ // A SIM to dial on: checked, and absent from older phones' messages.+ assert!(CallDial { number: "555".into(), sim: Some("1".into()) }.is_valid());+ assert!(!CallDial { number: "555".into(), sim: Some(String::new()) }.is_valid());+ assert!(!CallDial { number: "555".into(), sim: Some("a\nb".into()) }.is_valid());+ let old = Envelope::new(types::CALL_DIAL, &CallDial { number: "555".into(), sim: None }).unwrap();+ assert_eq!(old.body::<CallDial>().unwrap().sim, None);+ let sims = CallSims {+ sims: vec![+ CallSim { id: "1".into(), label: "SIM 1 · Airtel".into() },+ CallSim { id: "2".into(), label: "SIM 2 · Jio".into() },+ ],+ default: Some("2".into()),+ };+ assert!(sims.is_valid());+ let env = Envelope::new(types::CALL_SIMS, &sims).unwrap();+ assert_eq!(env.body::<CallSims>().unwrap(), sims);+ assert!(!CallSims { default: Some("3".into()), ..sims.clone() }.is_valid());+ assert!(+ !CallSims { sims: vec![sims.sims[0].clone(); calls::MAX_SIMS + 1], default: None }.is_valid()+ );let entry = CallLogEntry {id: "10".into(),@@ -5766,6 +5830,7 @@ mod tests {CallAction,CallLog,CallDial,+ CallSims,SmsThreads,SmsMessages,SmsSend,diff --git a/desktop/app/qml/pages/CallsPage.qml b/desktop/app/qml/pages/CallsPage.qmlindex 9e9ae12..de0e914 100644--- a/desktop/app/qml/pages/CallsPage.qml+++ b/desktop/app/qml/pages/CallsPage.qml@@ -812,6 +812,27 @@ Item {}}+ // Which SIM calls go out on, when the phone has more than one+ // (otherwise Android asks on the phone, where nobody sees it).+ Row {+ id: simChoice+ readonly property var sims: { try { return JSON.parse(PhoneCall.sims || "[]") } catch (e) { return [] } }+ visible: sims.length > 1 && PhoneCall.canDial+ anchors.horizontalCenter: parent.horizontalCenter+ spacing: 10+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ text: qsTr("Call with")+ role: "body"+ muted: true+ }+ Segmented {+ options: simChoice.sims.map(s => ({ value: s.id, label: s.label }))+ value: PhoneCall.sim+ onPicked: (v) => PhoneCall.chooseSim(v)+ }+ }+LockChip {anchors.horizontalCenter: parent.horizontalCentervisible: !PhoneCall.canDial && label.length > 0diff --git a/desktop/app/src/bridge/calls.rs b/desktop/app/src/bridge/calls.rsindex d82222d..96aec30 100644--- a/desktop/app/src/bridge/calls.rs+++ b/desktop/app/src/bridge/calls.rs@@ -58,6 +58,10 @@ pub mod qobject {#[qproperty(bool, can_dial, cxx_name = "canDial")]/// A dial request is on its way to the phone.#[qproperty(bool, dialing)]+ /// The phone's SIMs as JSON `[{ id, label }]`, when it has more than one.+ #[qproperty(QString, sims)]+ /// The SIM calls go out on (an id from `sims`), or `""`.+ #[qproperty(QString, sim)]/// Whether a paired Bluetooth HFP / audio playback endpoint is available for the phone.#[qproperty(bool, hfp_available, cxx_name = "hfpAvailable")]/// Whether call audio is currently routed through this PC over Bluetooth.@@ -89,6 +93,10 @@ pub mod qobject {/// Asks the phone to dial `number`.#[qinvokable]fn dial(self: &PhoneCall, number: &QString);+ /// Calls go out on the SIM `sim` (an id from `sims`) from now on.+ #[qinvokable]+ #[cxx_name = "chooseSim"]+ fn choose_sim(self: &PhoneCall, sim: &QString);/// Puts text on this PC's clipboard (it isn't sent back to the phone).#[qinvokable]fn copy(self: &PhoneCall, text: &QString);@@ -146,6 +154,8 @@ pub struct PhoneCallRust {contacts: QString,can_dial: bool,dialing: bool,+ sims: QString,+ sim: QString,hfp_available: bool,hfp_connected: bool,hfp_detail: QString,@@ -161,6 +171,7 @@ impl cxx_qt::Initialize for qobject::PhoneCall {self.as_mut().set_call_log(QString::from("[]"));self.as_mut().set_contacts_status(QString::from("idle"));self.as_mut().set_contacts(QString::from("[]"));+ self.as_mut().set_sims(QString::from("[]"));super::subscribe(self.qt_thread(), Changes::CALLS | Changes::CAPABILITIES, Self::refresh_state);}}@@ -200,6 +211,12 @@ impl qobject::PhoneCall {calls::load_older();}+ pub fn choose_sim(&self, sim: &QString) {+ if let Some(device) = super::parse_device(&self.rust().device) {+ calls::choose_sim(device, String::from(sim));+ }+ }+pub fn dial(&self, number: &QString) {if let Some(device) = super::parse_device(&self.rust().device) {calls::dial(device, String::from(number));@@ -275,6 +292,10 @@ impl qobject::PhoneCall {self.as_mut().set_contacts(QString::from(&view.contacts.to_string()));}self.as_mut().set_dialing(view.dialing);+ if differs(|v| v.sims.to_string()) {+ self.as_mut().set_sims(QString::from(&view.sims.to_string()));+ }+ self.as_mut().set_sim(QString::from(&view.sim));self.as_mut().rust_mut().last_view = Some(view);}}diff --git a/desktop/app/src/calls.rs b/desktop/app/src/calls.rsindex 94fb8bb..f7baaac 100644--- a/desktop/app/src/calls.rs+++ b/desktop/app/src/calls.rs@@ -8,7 +8,7 @@use crate::i18n::tr;use std::{collections::{HashMap, HashSet},- path::PathBuf,+ path::{Path, PathBuf},sync::{Mutex,atomic::{AtomicBool, Ordering},@@ -16,7 +16,8 @@ use std::{};use nectarlink_core::{- CallCommand, CallLogEntry, CallState, Contact, DeviceId, Error, FeatureState, LinkState, NodeEvent,+ CallCommand, CallLogEntry, CallSims, CallState, Contact, DeviceId, Error, FeatureState, LinkState,+ NodeEvent,};use serde_json::{Value, json};@@ -473,6 +474,8 @@ struct PageState {contacts_status: Status,contacts: Vec<Contact>,dialing: bool,+ /// The phone's SIMs, to pick which one calls (#112).+ sims: CallSims,/// Caller photos saved, by call log entry ID.log_photos: HashMap<String, PathBuf>,/// Contact photos saved, by contact ID.@@ -517,6 +520,10 @@ pub struct View {pub contacts_status: Status,pub contacts: Value,pub dialing: bool,+ /// `[{ id, label }]` when the phone has more than one SIM to call with.+ pub sims: Value,+ /// The SIM calls go out on (an id from `sims`), or `""`.+ pub sim: String,}pub fn view() -> View {@@ -565,10 +572,94 @@ pub fn view() -> View {s.contacts.iter().map(|c| contact_json(c, s.contact_photos.get(&c.id))).collect(),),dialing: s.dialing,+ sims: if s.sims.sims.len() > 1 {+ Value::Array(+ s.sims.sims.iter().map(|sim| json!({ "id": sim.id, "label": sim.label })).collect(),+ )+ } else {+ Value::Array(Vec::new())+ },+ sim: s.device.and_then(|d| sim_from(&s.sims, chosen_sim(d).as_deref())).unwrap_or_default(),}})}+// ---- SIM choice (#112) ----++/// The SIM picked for each phone, kept in `call-sims.json`.+static CHOSEN_SIMS: Mutex<Option<HashMap<DeviceId, String>>> = Mutex::new(None);++fn sims_file() -> PathBuf {+ core_host::host().data_dir.join("call-sims.json")+}++fn load_chosen(path: &Path) -> HashMap<DeviceId, String> {+ std::fs::read(path)+ .ok()+ .and_then(|b| serde_json::from_slice::<HashMap<String, String>>(&b).ok())+ .map(|m| m.into_iter().filter_map(|(k, v)| Some((k.parse().ok()?, v))).collect())+ .unwrap_or_default()+}++fn save_chosen(path: &Path, chosen: &HashMap<DeviceId, String>) -> std::io::Result<()> {+ let plain: HashMap<String, &String> = chosen.iter().map(|(k, v)| (k.to_string(), v)).collect();+ let tmp = path.with_extension("json.tmp");+ std::fs::write(&tmp, serde_json::to_vec(&plain).map_err(std::io::Error::other)?)?;+ std::fs::rename(&tmp, path)+}++fn chosen_sim(device: DeviceId) -> Option<String> {+ let mut guard = CHOSEN_SIMS.lock().unwrap_or_else(|e| e.into_inner());+ guard.get_or_insert_with(|| load_chosen(&sims_file())).get(&device).cloned()+}++/// The SIM to call on with `sims`: the one picked if it's still there, else+/// the phone's own default, else the first when there's a choice to make.+/// `None` when the phone has one SIM or doesn't list them.+fn sim_from(sims: &CallSims, chosen: Option<&str>) -> Option<String> {+ if sims.sims.len() < 2 {+ return None;+ }+ chosen+ .filter(|c| sims.sims.iter().any(|s| s.id == *c))+ .or(sims.default.as_deref())+ .or(sims.sims.first().map(|s| s.id.as_str()))+ .map(str::to_owned)+}++/// Calls from this PC to `device` go out on `sim` from now on.+pub fn choose_sim(device: DeviceId, sim: String) {+ {+ let mut guard = CHOSEN_SIMS.lock().unwrap_or_else(|e| e.into_inner());+ let chosen = guard.get_or_insert_with(|| load_chosen(&sims_file()));+ chosen.insert(device, sim);+ if let Err(e) = save_chosen(&sims_file(), chosen) {+ tracing::warn!(error = %e, "can't save the SIM choice");+ }+ }+ page_changed();+}++fn load_sims() {+ let Some((device, generation)) = page_state(|s| s.device.map(|d| (d, s.generation))) else { return };+ let Some(node) = core_host::node() else { return };+ core_host::spawn(async move {+ let sims = match node.call_sims(device).await {+ Ok(sims) => sims,+ Err(e) => {+ tracing::debug!(error = %e, "can't list the phone's SIMs");+ return;+ }+ };+ page_state(|s| {+ if s.generation == generation {+ s.sims = sims;+ }+ });+ page_changed();+ });+}+fn log_entry_json(e: &CallLogEntry, name: &str, photo: String) -> Value {json!({"id": e.id,@@ -616,6 +707,7 @@ pub fn open_device(device: DeviceId) {}load_call_log(None);load_contacts();+ load_sims();}/// Loads `device`'s contacts in the background if not already loaded for it@@ -639,6 +731,7 @@ pub fn reload() {refresh_hfp_cache_async(dev);load_call_log(None);load_contacts();+ load_sims();}pub fn load_older() {@@ -826,11 +919,20 @@ pub fn dial(device: DeviceId, number: String) {if number.is_empty() {return;}- page_state(|s| s.dialing = true);+ // The SIM picked on the Calls page, also for a call started elsewhere+ // (Messages, the command palette).+ let sim = page_state(|s| {+ s.dialing = true;+ if s.device == Some(device) {+ sim_from(&s.sims, chosen_sim(device).as_deref())+ } else {+ chosen_sim(device)+ }+ });page_changed();let Some(node) = core_host::node() else { return };core_host::spawn(async move {- let result = node.call_dial(device, number).await;+ let result = node.call_dial(device, number, sim).await;page_state(|s| s.dialing = false);page_changed();if let Err(e) = result {@@ -1053,4 +1155,31 @@ mod tests {assert_eq!(dial_problem(&Error::Denied), "Calls are turned off for this phone.");assert_eq!(dial_problem(&Error::Offline), "The phone isn't connected.");}++ #[test]+ fn the_sim_is_the_picked_one_then_the_phones_default_then_the_first() {+ use nectarlink_core::CallSim;+ let sim = |id: &str| CallSim { id: id.into(), label: format!("SIM {id}") };+ let two = CallSims { sims: vec![sim("1"), sim("2")], default: None };+ assert_eq!(sim_from(&two, None).as_deref(), Some("1"));+ assert_eq!(sim_from(&two, Some("2")).as_deref(), Some("2"));+ // A SIM taken out since: the next best.+ assert_eq!(sim_from(&two, Some("9")).as_deref(), Some("1"));+ let with_default = CallSims { default: Some("2".into()), ..two.clone() };+ assert_eq!(sim_from(&with_default, None).as_deref(), Some("2"));+ assert_eq!(sim_from(&with_default, Some("1")).as_deref(), Some("1"));+ // One SIM, or none listed: nothing to pick, the phone decides.+ assert_eq!(sim_from(&CallSims { sims: vec![sim("1")], default: None }, Some("1")), None);+ assert_eq!(sim_from(&CallSims::default(), None), None);+ }++ #[test]+ fn sim_choices_round_trip_through_their_file() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("call-sims.json");+ let phone = DeviceId([3; 32]);+ save_chosen(&path, &HashMap::from([(phone, "2".to_owned())])).unwrap();+ assert_eq!(load_chosen(&path).get(&phone).map(String::as_str), Some("2"));+ assert!(load_chosen(&dir.path().join("missing.json")).is_empty());+ }}diff --git a/docs/guide/calls.md b/docs/guide/calls.mdindex ae1c1cd..87a9de8 100644--- a/docs/guide/calls.md+++ b/docs/guide/calls.md@@ -39,6 +39,7 @@ While a call is active on your phone, the call bar on your PC shows the live cal1. Open **Calls** in the left navigation bar on your PC.2. You can start a call in three ways:- **From the Keypad**: Type or paste a phone number into the dialer keypad (or press number keys on your keyboard) and click **Call**.+ - **With two SIMs**: Pick the SIM under **Call with** next to the keypad. The PC remembers it for that phone and uses it for every call it starts, so the phone doesn't stop to ask which SIM.- **From Contacts**: Search your synced phone contacts (favorites appear at the top) and click the call button next to any number.- **From Recent Calls**: Click any entry in your recent call history to call back or open a text conversation with that person.3. Your phone places the cellular call immediately.diff --git a/docs/protocol/calls.md b/docs/protocol/calls.mdindex 94e9a11..650f6a8 100644--- a/docs/protocol/calls.md+++ b/docs/protocol/calls.md@@ -19,6 +19,7 @@ carries no sound.| `call.incall` | phone | Also mutes, switches to the speaker, holds and presses keys on the call in progress, and reports those `controls` || `call.log` | phone | Lists recent calls (needs the call log permission) || `call.dial` | phone | Places a call (or opens the dialer with the number filled in) when a PC asks |+| `call.sims` | phone | Lists the SIMs it calls with, and places a call on the one a PC picks || `call.show` | PC | Shows calls, recent calls and the dialer, and wants `call.log.changed` |A phone reports calls and answers call requests only for PCs that offer@@ -60,9 +61,12 @@ t = "call.log" re = n b = { entries: [ call_entry ] } //t = "call.log.changed" b = {} // phone → PC-t = "call.dial" id = n b = { number: text }+t = "call.dial" id = n b = { number: text, ? sim: text } // sim: an id from call.simst = "ok" re = n+t = "call.sims" id = n b = {}+t = "call.sims" re = n b = { sims: [ { id: text, label: text } ], ? default: text }+call_entry = {id: text,number: text, // Who called, or who was called ("" when withheld)@@ -127,16 +131,36 @@ dialer (`Intent.ACTION_DIAL`) with the number filled in. Once the callstarts, the phone reports it through `call.state`, so the PC's call cardand in-call controls work as for any call.+With `sim` (an `id` from `call.sims`, 1 to 64 bytes), a phone that offers+`call.sims` places the call on that SIM, or on its default if the SIM is+gone; phones from before `sim` ignore it. A PC sends `sim` only to a phone+that offers `call.sims`.+Errors: `DENIED` when calls are off for the PC, `UNSUPPORTED` when thephone doesn't offer `call.dial`, `INTERNAL` when the phone couldn't startthe call.+### 2.4.1 `call.sims`++`call.sims` asks which SIMs (and calling apps, such as a SIP account) the+phone places calls with: at most 8, each with an `id` that stays the same+while the SIM is in and a `label` as Android shows it ("SIM 1 · Airtel"),+and `default` when the phone calls with one without asking. A phone set to+ask each time has no `default`, and Android would ask on the phone, where+nobody at the PC sees it, so the PC picks one: the user's choice for that+phone, else the first. With one SIM there's nothing to pick.++Errors: `DENIED` when calls are off for the PC, `UNSUPPORTED` when the+phone doesn't offer `call.sims`.+### 2.5 On Android`call.control` needs the phone permission and the permission to answercalls. `call.log` needs the call log permission. `call.dial` uses`CALL_PHONE` to place the call directly, or opens the dialer when-`CALL_PHONE` isn't granted. `call.incall` needs Android 12 or later and+`CALL_PHONE` isn't granted. `call.sims` needs `CALL_PHONE` and+`READ_PHONE_STATE`: it lists `TelecomManager.getCallCapablePhoneAccounts()`+and calls with `EXTRA_PHONE_ACCOUNT_HANDLE`. `call.incall` needs Android 12 or later andthe `MANAGE_ONGOING_CALLS` app-op, which lets Telecom bind NectarLink'sin-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