Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Contacts, the call log, and calling from the PC
Bee7a0182b152eb
diff --git a/README.md b/README.mdindex 0049ab2..7e8da18 100644--- a/README.md+++ b/README.md@@ -105,15 +105,19 @@ tests; there are no releases yet.window of its own, running on the phone beside whatever its screenshows; use it with the mouse and keyboard, and open several at once.- **Texts** on the PC: a Messages page with the phone's conversations- (pictures included), to reply or start a new one; texts go out through- the phone. Search them, copy a one-time code with one click, and open- links.-- **Calls**: see who's calling on the PC (with the contact's name and- photo), and answer, decline or silence it from there. During the call,- the PC shows how long it has been going and can hang up and change the- volume; with Wireless debugging set up (Android 12 and later), also mute,- switch to the speaker, hold and use the keypad. The call itself stays- on the phone. Calls nobody answered show as missed.+ (pictures included), to reply or start a new one (searching contacts as+ you type); texts go out through the phone. Search them, copy a one-time+ code with one click, and open links.+- **Calls and contacts**: a Calls page with the phone's recent calls+ (grouped by day, missed calls marked, tap to call back or text), its+ contacts (favorites first, with photos and search), and a keypad to call+ any number from the PC through the phone. When the phone rings, see who's+ calling on the PC (with the contact's name and photo), and answer, decline+ or silence it from there. During the call, the PC shows how long it has+ been going and can hang up and change the volume; with Wireless debugging+ set up (Android 12 and later), also mute, switch to the speaker, hold and+ use the keypad. The call's audio stays on the phone. Calls nobody answered+ show as missed.- **New photos and screenshots** from the phone pop up on the PC with apreview: save them to Downloads or copy them, ready to paste.- **Media** both ways: what plays on the phone shows on the PC, in the app and@@ -125,7 +129,7 @@ tests; there are no releases yet.- **Capability matrix**: both apps compute which features work for a pair ofdevices and what would enable the rest, so the interface never offerssomething that can't work.-- **Windows app**: home, messages and settings, two themes in light and dark (Bloom,+- **Windows app**: home, messages, calls and settings, two themes in light and dark (Bloom,which takes its colors from the desktop wallpaper, and Graphite), Mica, acustom title bar with Snap Layouts, and a tray icon. In the background ituses about 10 MB of memory (as shown in Task Manager).@@ -140,7 +144,7 @@ tests; there are no releases yet.against their SHA-256 sums.- **Command-line client** for development and testing (`nectarlink`).-**Next**: contacts and the call log, talking on calls through the PC (Bluetooth), and the rest of the+**Next**: talking on calls through the PC (Bluetooth), and the rest of the[plan](docs/PLAN.md).## Screenshotsdiff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex db5add3..ed1faed 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -40,6 +40,7 @@<uses-permission android:name="android.permission.READ_PHONE_STATE" /><uses-permission android:name="android.permission.READ_CALL_LOG" /><uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />+ <uses-permission android:name="android.permission.CALL_PHONE" /><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. -->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 f020f21..7949d07 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@@ -8,6 +8,8 @@ import android.content.Contextimport android.content.Intentimport android.content.IntentFilterimport android.content.pm.PackageManager+import android.database.ContentObserver+import android.database.Cursorimport android.graphics.Bitmapimport android.graphics.BitmapFactoryimport android.media.AudioManager@@ -21,28 +23,41 @@ import android.telecom.TelecomManagerimport android.telephony.TelephonyManagerimport android.util.Logimport androidx.core.content.ContextCompat+import app.nectarlink.android.contacts.PhoneContactsimport app.nectarlink.core.Callimport app.nectarlink.core.CallCommand+import app.nectarlink.core.CallLogEntryimport app.nectarlink.core.CallPhaseimport java.io.ByteArrayOutputStreamimport java.util.concurrent.Executors/*** The phone's calls, for PCs (docs/protocol/calls.md): follows the call- * state while the app runs, and answers, declines or silences a ringing- * call when a PC asks. The call's audio stays on the phone.+ * state while the app runs, answers, declines or silences a ringing+ * call when a PC asks, lists recent calls (`call.log`), and places calls+ * (`call.dial`). The call's audio stays on the phone.*/-internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unit) {+internal class PhoneCalls(+ context: Context,+ private val onChange: (Call) -> Unit,+ private val onLogChanged: () -> Unit = {},+) {private val context = context.applicationContextprivate val main = Handler(Looper.getMainLooper())/** Contact lookups and reports, in order, off the main thread. */private val worker = Executors.newSingleThreadExecutor()private var receiver: BroadcastReceiver? = null+ private var logObserver: ContentObserver? = null+ private val notifyLog = Runnable { onLogChanged() }/** The call in progress (changed on the main thread, read by PCs' requests). */@Volatileprivate var current: Tracked? = null+ /** Number dialed from a PC, used when Android's OFFHOOK broadcast omits the number. */+ @Volatile+ private var lastDialed: Pair<String, Long>? = null+private data class Tracked(val id: String,val incoming: Boolean,@@ -56,30 +71,46 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unitfun start() {instance = this- if (receiver != null || !canFollow(context)) return- receiver = object : BroadcastReceiver() {- override fun onReceive(context: Context, intent: Intent) {- val state = intent.getStringExtra(TelephonyManager.EXTRA_STATE) ?: return- // Only sent with the call log permission; a second broadcast- // carries it when there is one.- @Suppress("DEPRECATION")- val number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)- stateChanged(state, number?.takeIf { it.isNotBlank() })+ if (receiver == null && canFollow(context)) {+ receiver = object : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ val state = intent.getStringExtra(TelephonyManager.EXTRA_STATE) ?: return+ // Only sent with the call log permission; a second broadcast+ // carries it when there is one.+ @Suppress("DEPRECATION")+ val number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)+ stateChanged(state, number?.takeIf { it.isNotBlank() })+ }+ }.also {+ ContextCompat.registerReceiver(+ context,+ it,+ IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED),+ // A system broadcast: other apps can't send it here.+ ContextCompat.RECEIVER_NOT_EXPORTED,+ )}- }.also {- ContextCompat.registerReceiver(- context,- it,- IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED),- // A system broadcast: other apps can't send it here.- ContextCompat.RECEIVER_NOT_EXPORTED,- )+ }+ if (logObserver == null && canReadLog(context)) {+ runCatching {+ logObserver = object : ContentObserver(main) {+ override fun onChange(selfChange: Boolean) {+ main.removeCallbacks(notifyLog)+ main.postDelayed(notifyLog, LOG_SETTLE_MS)+ }+ }.also {+ context.contentResolver.registerContentObserver(CallLog.Calls.CONTENT_URI, true, it)+ }+ }.onFailure { Log.w(TAG, "couldn't watch call log", it) }}}fun stop() {receiver?.let { runCatching { context.unregisterReceiver(it) } }receiver = null+ logObserver?.let { runCatching { context.contentResolver.unregisterContentObserver(it) } }+ logObserver = null+ main.removeCallbacks(notifyLog)current = null}@@ -102,11 +133,16 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unitcall == null -> {// Calling out.val now = System.currentTimeMillis()- val tracked = Tracked(id = now.toString(), incoming = false, number = number, answered = true, since = now)+ val dialed = lastDialed?.takeIf { now - it.second < 15_000L }?.first+ val outNumber = number ?: dialed+ val tracked = Tracked(id = now.toString(), incoming = false, number = outNumber, answered = true, since = now)current = tracked- report(tracked, CallPhase.ACTIVE, withContact = false)+ report(tracked, CallPhase.ACTIVE, withContact = true)}!call.answered -> {+ if (call.number == null && number != null) {+ call.number = number+ }call.answered = truecall.since = System.currentTimeMillis()report(call, CallPhase.ACTIVE, withContact = false)@@ -114,6 +150,7 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unit}TelephonyManager.EXTRA_STATE_IDLE -> if (call != null) {current = null+ lastDialed = nullrestoreRinger()if (call.incoming && !call.answered && !call.declined) {// Missed, or turned down on the phone: the call log knows,@@ -152,7 +189,7 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unitincoming = incoming,number = number,name = name,- photo = photo.takeIf { phase == CallPhase.RINGING },+ photo = photo.takeIf { phase == CallPhase.RINGING || (!incoming && phase == CallPhase.ACTIVE) },missed = missed,since = since.takeIf { phase == CallPhase.ACTIVE },controls = if (phase == CallPhase.ACTIVE) CallCompanion.controls() else null,@@ -213,7 +250,7 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unitval date = cursor.getLong(1)val loggedNumber = cursor.getString(2)if (started > 0L && date < started - 10_000L) return@use true- if (number != null && !loggedNumber.isNullOrBlank() && !android.telephony.PhoneNumberUtils.compare(context, number, loggedNumber)) {+ if (number != null && !loggedNumber.isNullOrBlank() && !sameNumber(number, loggedNumber)) {return@use true}cursor.getInt(0) == CallLog.Calls.MISSED_TYPE@@ -221,6 +258,12 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unit}.getOrDefault(true)}+ private fun sameNumber(a: String, b: String): Boolean {+ val da = a.filter { it.isDigit() }.takeLast(9)+ val db = b.filter { it.isDigit() }.takeLast(9)+ return da.isNotEmpty() && da == db+ }+/*** Runs what a PC asked; false if the phone couldn't. The companion* (when Telecom has bound it) controls the call itself; otherwise@@ -262,6 +305,121 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unit}}+ /** Recent calls from the phone's call history (`call.log`). */+ @SuppressLint("MissingPermission")+ fun callLog(before: Long?, limit: Int): List<CallLogEntry> {+ check(canReadLog(context)) { "Call log permission not granted" }+ return try {+ val resolver = context.contentResolver+ val contactsAllowed = granted(context, Manifest.permission.READ_CONTACTS)+ val contactCache = HashMap<String, Pair<String?, ByteArray?>>()+ fun lookupContact(number: String, cachedName: String?, cachedPhotoUri: String?): Pair<String?, ByteArray?> =+ contactCache.getOrPut(number) {+ var name = cachedName?.trim()?.takeIf { it.isNotEmpty() }+ var photoUri = cachedPhotoUri?.trim()?.takeIf { it.isNotEmpty() }+ if ((name == null || photoUri == null) && contactsAllowed) {+ runCatching {+ val uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number))+ val cols = arrayOf(+ ContactsContract.PhoneLookup.DISPLAY_NAME,+ ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI,+ )+ resolver.query(uri, cols, null, null, null)?.use { c: Cursor ->+ if (c.moveToFirst()) {+ if (name == null) name = c.getString(0)?.trim()?.takeIf { it.isNotEmpty() }+ if (photoUri == null) photoUri = c.getString(1)?.trim()?.takeIf { it.isNotEmpty() }+ }+ }+ }+ }+ val photo = photoUri?.let(Uri::parse)?.let { PhoneContacts.smallPhoto(resolver, it) }+ name to photo+ }++ val columns = arrayOf(+ CallLog.Calls._ID,+ CallLog.Calls.NUMBER,+ CallLog.Calls.CACHED_NAME,+ CallLog.Calls.TYPE,+ CallLog.Calls.DATE,+ CallLog.Calls.DURATION,+ CallLog.Calls.CACHED_PHOTO_URI,+ )+ val (selection, args) = if (before == null) {+ null to null+ } else {+ "${CallLog.Calls.DATE} < ?" to arrayOf(before.toString())+ }+ val max = limit.coerceIn(1, MAX_LOG_PAGE)+ resolver.query(CallLog.Calls.CONTENT_URI, columns, selection, args, "${CallLog.Calls.DATE} DESC")?.use { c ->+ buildList {+ while (size < max && c.moveToNext()) {+ val number = c.getString(1)?.trim().orEmpty()+ if (number.isEmpty()) continue+ val direction = when (c.getInt(3)) {+ CallLog.Calls.OUTGOING_TYPE -> "outgoing"+ CallLog.Calls.MISSED_TYPE -> "missed"+ CallLog.Calls.REJECTED_TYPE, CallLog.Calls.BLOCKED_TYPE -> "rejected"+ else -> "incoming"+ }+ val (name, photo) = lookupContact(number, c.getString(2), c.getString(6))+ add(+ CallLogEntry(+ id = c.getLong(0).toString(),+ number = number,+ name = name,+ direction = direction,+ date = c.getLong(4),+ duration = c.getLong(5).coerceIn(0L, UInt.MAX_VALUE.toLong()).toUInt(),+ photo = photo,+ ),+ )+ }+ }+ }.orEmpty()+ } catch (e: Exception) {+ Log.w(TAG, "can't read call log", e)+ emptyList()+ }+ }++ /**+ * Places a call (`TelecomManager.placeCall` / `Intent.ACTION_CALL` when+ * `CALL_PHONE` is granted), or falls back to opening the dialer with the+ * number pre-filled (`Intent.ACTION_DIAL`).+ */+ @SuppressLint("MissingPermission")+ fun dial(number: String): Boolean {+ val trimmed = number.trim()+ if (trimmed.isEmpty()) return false+ lastDialed = trimmed to System.currentTimeMillis()+ val uri = Uri.fromParts("tel", trimmed, null)+ return runCatching {+ if (granted(context, Manifest.permission.CALL_PHONE)) {+ val tm = context.getSystemService(TelecomManager::class.java)+ if (tm != null) {+ try {+ tm.placeCall(uri, android.os.Bundle.EMPTY)+ 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))+ return@runCatching true+ } catch (_: SecurityException) {+ // Fall back to the dialer below if the OS blocked direct calling.+ }+ }+ context.startActivity(Intent(Intent.ACTION_DIAL, uri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+ true+ }.getOrElse {+ Log.w(TAG, "couldn't dial a call", 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) }@@ -306,14 +464,17 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unitinstance?.resendActive()}private const val MAX_PHOTO_BYTES = 64 * 1024+ private const val MAX_LOG_PAGE = 100/** How long the call log takes to have the call that just ended. */private const val LOG_DELAY_MS = 1500L+ private const val LOG_SETTLE_MS = 500L- /** Following calls, with numbers, contact names, and answering. */+ /** Following calls, with numbers, contact names, answering, and calling. */val permissions: Array<String> = arrayOf(Manifest.permission.READ_PHONE_STATE,Manifest.permission.READ_CALL_LOG,Manifest.permission.ANSWER_PHONE_CALLS,+ Manifest.permission.CALL_PHONE,Manifest.permission.READ_CONTACTS,)@@ -327,6 +488,14 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unitfun canControl(context: Context) =canFollow(context) && granted(context, Manifest.permission.ANSWER_PHONE_CALLS)+ /** Whether it can read the phone's call history (`call.log`). */+ fun canReadLog(context: Context) = granted(context, Manifest.permission.READ_CALL_LOG)++ /** Whether it can place calls from a PC (`call.dial`). */+ fun canDial(context: Context) =+ context.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) &&+ (granted(context, Manifest.permission.CALL_PHONE) || canFollow(context))+/** 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/contacts/PhoneContacts.kt b/android/app/src/main/kotlin/app/nectarlink/android/contacts/PhoneContacts.ktnew file mode 100644index 0000000..a7e65bc--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/contacts/PhoneContacts.kt@@ -0,0 +1,182 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.contacts++import android.Manifest+import android.content.ContentResolver+import android.content.Context+import android.content.pm.PackageManager+import android.database.ContentObserver+import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.net.Uri+import android.os.Handler+import android.os.Looper+import android.provider.ContactsContract+import android.provider.ContactsContract.CommonDataKinds.Phone+import android.util.Log+import androidx.core.content.ContextCompat+import app.nectarlink.core.Contact+import app.nectarlink.core.ContactNumber+import java.io.ByteArrayOutputStream++/**+ * The phone's contacts with phone numbers, for PCs (docs/protocol/contacts.md):+ * lists and searches contacts (favorites first, then alphabetical) and+ * reports when the address book changes.+ */+internal class PhoneContacts(context: Context, private val onChange: () -> Unit) {+ private val context = context.applicationContext+ private val resolver = context.contentResolver+ private val handler = Handler(Looper.getMainLooper())+ private var observer: ContentObserver? = null+ private val notify = Runnable { onChange() }++ fun start() {+ if (observer != null || !canRead(context)) return+ runCatching {+ observer = object : ContentObserver(handler) {+ override fun onChange(selfChange: Boolean) {+ handler.removeCallbacks(notify)+ handler.postDelayed(notify, SETTLE_MS)+ }+ }.also {+ resolver.registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, it)+ }+ }.onFailure { Log.w(TAG, "couldn't watch contacts", it) }+ }++ fun stop() {+ observer?.let { runCatching { resolver.unregisterContentObserver(it) } }+ observer = null+ handler.removeCallbacks(notify)+ }++ private class Draft(+ val id: String,+ val name: String,+ val starred: Boolean,+ val photoUri: String?,+ val numbers: MutableList<ContactNumber> = ArrayList(2),+ val seenNumbers: HashSet<String> = HashSet(2),+ )++ fun list(query: String?, offset: Int, limit: Int): List<Contact> {+ check(canRead(context)) { "Contacts permission not granted" }+ return try {+ val drafts = LinkedHashMap<Long, Draft>()+ val columns = arrayOf(+ Phone.CONTACT_ID,+ Phone.DISPLAY_NAME_PRIMARY,+ Phone.STARRED,+ Phone.PHOTO_THUMBNAIL_URI,+ Phone.NUMBER,+ Phone.TYPE,+ Phone.LABEL,+ )+ val order = "${Phone.STARRED} DESC, ${Phone.DISPLAY_NAME_PRIMARY} COLLATE LOCALIZED ASC, ${Phone.CONTACT_ID} ASC"+ resolver.query(Phone.CONTENT_URI, columns, null, null, order)?.use { c ->+ while (c.moveToNext()) {+ val contactId = c.getLong(0)+ val name = c.getString(1)?.trim().orEmpty()+ val number = c.getString(4)?.trim().orEmpty()+ if (name.isEmpty() || number.isEmpty()) continue+ val draft = drafts.getOrPut(contactId) {+ Draft(+ id = contactId.toString(),+ name = name,+ starred = c.getInt(2) != 0,+ photoUri = c.getString(3),+ )+ }+ if (draft.numbers.size >= MAX_NUMBERS) continue+ val key = number.filter(Char::isDigit).ifEmpty { number }+ if (draft.seenNumbers.add(key)) {+ draft.numbers += ContactNumber(+ number = number,+ label = phoneLabel(c.getInt(5), c.getString(6)),+ )+ }+ }+ }+ val q = query?.trim()?.takeIf { it.isNotEmpty() }+ val qDigits = q?.filter(Char::isDigit).orEmpty()+ val filtered = if (q == null) {+ drafts.values.asSequence()+ } else {+ drafts.values.asSequence().filter { d ->+ d.name.contains(q, ignoreCase = true) ||+ d.numbers.any { n ->+ n.number.contains(q, ignoreCase = true) ||+ (qDigits.isNotEmpty() && n.number.filter(Char::isDigit).contains(qDigits))+ }+ }+ }+ filtered+ .drop(offset.coerceAtLeast(0))+ .take(limit.coerceIn(1, MAX_PAGE))+ .map { d ->+ Contact(+ id = d.id,+ name = d.name,+ numbers = d.numbers,+ starred = d.starred,+ photo = d.photoUri?.let(Uri::parse)?.let { smallPhoto(resolver, it) },+ )+ }+ .toList()+ } catch (e: Exception) {+ Log.w(TAG, "can't read contacts", e)+ emptyList()+ }+ }++ private fun phoneLabel(type: Int, custom: String?): String? = when (type) {+ Phone.TYPE_CUSTOM -> custom?.trim()?.takeIf { it.isNotEmpty() }+ Phone.TYPE_MOBILE -> "Mobile"+ Phone.TYPE_HOME -> "Home"+ Phone.TYPE_WORK -> "Work"+ Phone.TYPE_MAIN -> "Main"+ Phone.TYPE_FAX_WORK, Phone.TYPE_FAX_HOME -> "Fax"+ Phone.TYPE_PAGER -> "Pager"+ Phone.TYPE_OTHER -> "Other"+ else -> null+ }++ companion object {+ private const val TAG = "PhoneContacts"+ private const val SETTLE_MS = 500L+ private const val MAX_PAGE = 200+ private const val MAX_NUMBERS = 8+ private const val MAX_PHOTO_BYTES = 16 * 1024+ private const val PHOTO_EDGE = 96++ val permissions: Array<String> = arrayOf(Manifest.permission.READ_CONTACTS)++ fun canRead(context: Context): Boolean =+ ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) ==+ PackageManager.PERMISSION_GRANTED++ /** A contact thumbnail as a JPEG of at most 16 KiB. */+ internal fun smallPhoto(resolver: ContentResolver, uri: Uri): ByteArray? = runCatching {+ val raw = resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it) } ?: return null+ val bitmap = if (raw.width > PHOTO_EDGE || raw.height > PHOTO_EDGE) {+ Bitmap.createScaledBitmap(raw, PHOTO_EDGE, PHOTO_EDGE, true).also {+ if (it !== raw) raw.recycle()+ }+ } else {+ raw+ }+ try {+ generateSequence(85) { it - 15 }.takeWhile { it >= 40 }+ .map { q ->+ ByteArrayOutputStream().also {+ bitmap.compress(Bitmap.CompressFormat.JPEG, q, it)+ }.toByteArray()+ }+ .firstOrNull { it.size <= MAX_PHOTO_BYTES }+ } finally {+ bitmap.recycle()+ }+ }.getOrNull()+ }+}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 331fef5..96b113d 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@@ -19,6 +19,7 @@ import app.nectarlink.android.Rimport app.nectarlink.android.notifications.NotificationListenerimport app.nectarlink.android.calls.CallCompanionimport app.nectarlink.android.calls.PhoneCalls+import app.nectarlink.android.contacts.PhoneContactsimport app.nectarlink.android.elevated.Elevatedimport app.nectarlink.android.mirror.AppWindowsimport app.nectarlink.android.mirror.InputService@@ -73,7 +74,8 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerringer,phoneMedia,onLink = { pc, url -> LinkNotifications.show(this.context, _state.value.nameOf(pc).orEmpty(), url) },- onCall = { id, command -> calls.command(id, command) },+ calls = { calls },+ contacts = { contacts },sms = { sms },onMirror = { pc, request ->MirrorRequests.show(this.context, request, _state.value.nameOf(pc).orEmpty())@@ -83,10 +85,19 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerprivate val sms = PhoneSms(this.context) {notificationOps.trySend { it.smsChanged(null) }}- private val calls = PhoneCalls(this.context) { call ->- notificationOps.trySend { node ->- runCatching { node.callChanged(call) }.onFailure { Log.i(TAG, "a call wasn't reported", it) }- }+ private val calls = PhoneCalls(+ this.context,+ onChange = { call ->+ notificationOps.trySend { node ->+ runCatching { node.callChanged(call) }.onFailure { Log.i(TAG, "a call wasn't reported", it) }+ }+ },+ onLogChanged = {+ notificationOps.trySend { it.callLogChanged() }+ },+ )+ private val contacts = PhoneContacts(this.context) {+ notificationOps.trySend { it.contactsChanged() }}private val photos = RecentPhotos(this.context) { photo ->notificationOps.trySend { node ->@@ -167,6 +178,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerit.copy(photoAccess = RecentPhotos.hasAccess(context),callAccess = PhoneCalls.hasAll(context),+ contactsAccess = PhoneContacts.canRead(context),smsAccess = PhoneSms.hasAll(context),)}@@ -175,7 +187,8 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerscope.launch { Elevated.start() }scope.launch(Dispatchers.Main) {if (_state.value.photoAccess) photos.start()- if (PhoneCalls.canFollow(context)) calls.start()+ if (PhoneCalls.canFollow(context) || PhoneCalls.canReadLog(context)) calls.start()+ if (PhoneContacts.canRead(context)) contacts.start()if (PhoneSms.canRead(context)) sms.start()}scope.launch {@@ -220,6 +233,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerval unrestricted = BackgroundAccess.isUnrestricted(context)val photoAccess = RecentPhotos.hasAccess(context)val callAccess = PhoneCalls.hasAll(context)+ val contactsAccess = PhoneContacts.canRead(context)val smsAccess = PhoneSms.hasAll(context)val inputAccess = InputService.runningval elevated = Elevated.running@@ -234,6 +248,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerbackgroundUnrestricted = unrestricted,photoAccess = photoAccess,callAccess = callAccess,+ contactsAccess = contactsAccess,smsAccess = smsAccess,inputAccess = inputAccess,elevated = elevated,@@ -246,7 +261,8 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerif (node != null) {scope.launch(Dispatchers.Main) {if (photoAccess) photos.start() else photos.stop()- if (PhoneCalls.canFollow(context)) calls.start() else calls.stop()+ if (PhoneCalls.canFollow(context) || PhoneCalls.canReadLog(context)) calls.start() else calls.stop()+ if (contactsAccess) contacts.start() else contacts.stop()if (PhoneSms.canRead(context)) sms.start() else sms.stop()}notificationOps.trySend { it.updatePower(powerLevel(), capabilities(_state.value.notificationAccess)) }@@ -400,6 +416,9 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener(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 (PhoneCalls.canReadLog(context)) listOf("call.log") else emptyList()) ++ (if (PhoneCalls.canDial(context)) listOf("call.dial") 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()) +(if (InputService.running || Elevated.running) listOf("mirror.input") else emptyList()) +diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.ktindex 2f2c34b..99869f4 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt@@ -72,6 +72,8 @@ data class CoreState(val smsAccess: Boolean = false,/** Whether the user let Nectarlink follow and answer calls (to show them on PCs). */val callAccess: Boolean = false,+ /** Whether the user let Nectarlink read contacts (for PCs). */+ val contactsAccess: Boolean = false,/** Whether the user let Nectarlink see the phone's photos (to show new ones on PCs). */val photoAccess: Boolean = false,/** Whether Android lets Nectarlink run unrestricted in the background. */@@ -120,8 +122,14 @@ data class CoreState(is Event.Transfer -> copy(transfers = withTransfer(event.transfer))// Shown in Android's media controls (see media/PcMedia).is Event.MediaChanged -> this- // PCs only: phones announce their own photos, calls, texts and screen.- is Event.PhotoAdded, is Event.CallChanged, is Event.SmsChanged, is Event.Mirroring -> this+ // PCs only: phones announce their own photos, calls, contacts, texts and screen.+ is Event.PhotoAdded,+ is Event.CallChanged,+ is Event.CallLogChanged,+ is Event.ContactsChanged,+ is Event.SmsChanged,+ is Event.Mirroring,+ -> this}private fun withTransfer(transfer: Transfer): List<Transfer> {diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.ktindex 8b6bc98..7bac279 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@@ -8,7 +8,9 @@ import android.content.Contextimport android.content.Intentimport android.os.Buildimport android.os.Bundle+import app.nectarlink.android.calls.PhoneCallsimport app.nectarlink.android.clipboard.PhoneClipboard+import app.nectarlink.android.contacts.PhoneContactsimport app.nectarlink.android.notifications.NotificationListenerimport app.nectarlink.android.media.PhoneMediaimport app.nectarlink.android.photos.RecentPhotos@@ -20,6 +22,8 @@ import app.nectarlink.android.mirror.MirrorRequestsimport app.nectarlink.android.mirror.MirrorServiceimport app.nectarlink.android.sms.PhoneSmsimport app.nectarlink.core.CallCommand+import app.nectarlink.core.CallLogEntry+import app.nectarlink.core.Contactimport app.nectarlink.core.SmsMessageimport app.nectarlink.core.SmsPartDataimport app.nectarlink.core.SmsThread@@ -41,8 +45,10 @@ internal class PhonePlatform(private val media: PhoneMedia,/** Shows a link a PC sent: (PC's ID, link) → shown. */private val onLink: (String, String) -> Boolean,- /** Answers, declines or silences a call: (call ID, command) → done. */- private val onCall: (String, CallCommand) -> Boolean,+ /** The phone's calls (created after this). */+ private val calls: () -> PhoneCalls,+ /** The phone's contacts (created after this). */+ private val contacts: () -> PhoneContacts,/** The phone's texts (created after this). */private val sms: () -> PhoneSms,/** Asks the user to share the screen with a PC: (PC's ID, request) → asked. */@@ -68,7 +74,15 @@ internal class PhonePlatform(override fun openPhoto(id: String): FileToSend? = RecentPhotos.open(context, id)- override fun callCommand(id: String, command: CallCommand): Boolean = onCall(id, command)+ override fun callCommand(id: String, command: CallCommand): Boolean = calls().command(id, command)++ override fun callLog(before: Long?, limit: UInt): List<CallLogEntry> =+ calls().callLog(before, limit.toInt())++ override fun callDial(number: String): Boolean = calls().dial(number)++ override fun contacts(query: String?, offset: UInt, limit: UInt): List<Contact> =+ contacts().list(query, offset.toInt(), limit.toInt())override fun mirrorRequested(pcId: String, options: MirrorOptions): Boolean =if (options.app != null) {diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.ktindex 5023712..7eaa381 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt@@ -194,6 +194,7 @@ private fun App(core: Core, state: CoreState, preferences: Preferences) {onAppearance = preferences::update,onUnpair = core::unpair,onPairNew = { pairing = true },+ onAccessChanged = core::refreshNotificationAccess,updater = (LocalContext.current.applicationContext as NectarlinkApplication).updater,modifier = modifier,)diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.ktindex 49e5e9f..a51ae53 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt@@ -55,6 +55,7 @@ import app.nectarlink.android.core.CoreStateimport app.nectarlink.android.core.Deviceimport app.nectarlink.android.files.transferTitleimport app.nectarlink.android.calls.PhoneCalls+import app.nectarlink.android.contacts.PhoneContactsimport app.nectarlink.android.photos.RecentPhotosimport app.nectarlink.android.sms.PhoneSmsimport app.nectarlink.android.core.isFinished@@ -173,6 +174,17 @@ fun HomeScreen() { askCalls.launch(PhoneCalls.permissions) }}}+ if (state.devices.isNotEmpty() && !state.contactsAccess) {+ item {+ val askContacts = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {+ onAccessChanged()+ }+ SetupCard(+ stringResource(R.string.contacts_title),+ stringResource(R.string.contacts_off),+ ) { askContacts.launch(PhoneContacts.permissions) }+ }+ }if (state.devices.isNotEmpty() && !state.photoAccess) {item {val askPhotos = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.ktindex 66ebf2a..d0bdf48 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt@@ -44,11 +44,16 @@ import androidx.compose.ui.res.stringResourceimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.unit.dp+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContractsimport app.nectarlink.android.BuildConfigimport app.nectarlink.android.R+import app.nectarlink.android.calls.PhoneCalls+import app.nectarlink.android.contacts.PhoneContactsimport app.nectarlink.android.elevated.Elevatedimport app.nectarlink.android.elevated.PairingNotificationimport app.nectarlink.android.mirror.InputService+import app.nectarlink.android.sms.PhoneSmsimport app.nectarlink.android.update.AppUpdaterimport app.nectarlink.android.update.CheckForUpdatesimport app.nectarlink.android.core.CoreState@@ -66,6 +71,7 @@ fun SettingsScreen(onAppearance: ((Appearance) -> Appearance) -> Unit,onUnpair: (String) -> Unit,onPairNew: () -> Unit,+ onAccessChanged: () -> Unit,updater: AppUpdater,modifier: Modifier = Modifier,) {@@ -85,6 +91,33 @@ fun SettingsScreen(NotificationAccess(state.notificationAccess)}+ Section(stringResource(R.string.settings_calls_and_contacts)) {+ RuntimePermissionAccess(+ title = stringResource(R.string.calls_title),+ textOn = stringResource(R.string.calls_on),+ textOff = stringResource(R.string.calls_off),+ granted = state.callAccess,+ permissions = PhoneCalls.permissions,+ onAccessChanged = onAccessChanged,+ )+ RuntimePermissionAccess(+ title = stringResource(R.string.contacts_title),+ textOn = stringResource(R.string.contacts_on),+ textOff = stringResource(R.string.contacts_off),+ granted = state.contactsAccess,+ permissions = PhoneContacts.permissions,+ onAccessChanged = onAccessChanged,+ )+ RuntimePermissionAccess(+ title = stringResource(R.string.sms_title),+ textOn = stringResource(R.string.sms_on),+ textOff = stringResource(R.string.sms_off),+ granted = state.smsAccess,+ permissions = PhoneSms.permissions,+ onAccessChanged = onAccessChanged,+ )+ }+Section(stringResource(R.string.settings_control)) {ControlAccess(state.inputAccess)ElevatedAccess()@@ -313,6 +346,41 @@ private fun ElevatedAccess() {}}+@Composable+private fun RuntimePermissionAccess(+ title: String,+ textOn: String,+ textOff: String,+ granted: Boolean,+ permissions: Array<String>,+ onAccessChanged: () -> Unit,+) {+ val context = LocalContext.current+ val ask = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {+ onAccessChanged()+ }+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.weight(1f).padding(end = 12.dp)) {+ Text(title, style = MaterialTheme.typography.titleSmall)+ Text(+ if (granted) textOn else textOff,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ if (granted) {+ OutlinedButton(onClick = {+ context.startActivity(+ Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", context.packageName, null))+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+ )+ }) { Text(stringResource(R.string.action_manage)) }+ } else {+ Button(onClick = { ask.launch(permissions) }) { Text(stringResource(R.string.action_allow)) }+ }+ }+}+@Composableprivate fun Section(title: String, content: @Composable () -> Unit) {Text(diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex 88add62..433dbbb 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -108,10 +108,16 @@</plurals><string name="app_windows_text">Shown on %1$s. They run here, beside what\'s on your screen.</string><string name="action_close_all">Close all</string>+ <string name="settings_calls_and_contacts">Calls, contacts and messages</string><string name="sms_title">Text from your PC</string>+ <string name="sms_on">On. Conversations appear on your PC, where you can read and send texts.</string><string name="sms_off">Read your conversations and send texts from your PC. Nectarlink needs access to your messages and contacts for that.</string>- <string name="calls_title">Show calls on your PC</string>- <string name="calls_off">See who’s calling on your PC, and answer or decline from there. The call itself stays on your phone. Nectarlink needs access to calls and contacts for that.</string>+ <string name="calls_title">Calls on your PC</string>+ <string name="calls_on">On. Recent calls and incoming calls appear on your PC, and you can start or answer calls from there.</string>+ <string name="calls_off">See who’s calling, browse recent calls, and start or answer calls from your PC. The call itself stays on your phone. Nectarlink needs access to calls, call history, and contacts for that.</string>+ <string name="contacts_title">Contacts on your PC</string>+ <string name="contacts_on">On. Your contacts are available in Calls and Messages on your PC.</string>+ <string name="contacts_off">Search your contacts and start a call or text from your PC. Nectarlink needs access to your contacts for that.</string><string name="photos_title">Show new photos on your PC</string><string name="photos_off">Screenshots and photos you take pop up on your PC, ready to save or paste. Nectarlink needs access to your photos for that.</string><string name="transfer_too_many">That folder has too many files to send at once.</string>diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex 5b0716a..0140769 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -272,6 +272,25 @@ enum Command {#[arg(long)]script: Option<String>,},+ /// List a paired phone's recent calls, or call a number with `call <device> <number>`.+ Call {+ device: String,+ /// Number to call (omit to list recent calls).+ number: Option<String>,+ /// Max recent calls to list when no number is given.+ #[arg(long, default_value_t = 30)]+ limit: u32,+ },+ /// List or search a paired phone's contacts.+ Contacts {+ device: String,+ /// Search by name or number.+ query: Option<String>,+ #[arg(long, default_value_t = 0)]+ offset: u32,+ #[arg(long, default_value_t = 50)]+ limit: u32,+ },/// Announce a picture as a photo just taken on this phone (use with/// --as-phone), then stay online to send it to PCs that ask.Photo {@@ -628,6 +647,103 @@ fn sample_texts() {.collect();}+static CONTACTS: std::sync::Mutex<Vec<nectarlink_core::Contact>> = std::sync::Mutex::new(Vec::new());+static CALL_LOG: std::sync::Mutex<Vec<nectarlink_core::CallLogEntry>> = std::sync::Mutex::new(Vec::new());++fn sample_contacts() {+ use nectarlink_core::{Contact, ContactNumber};+ let num = |number: &str, label: &str| ContactNumber {+ number: number.into(),+ label: (!label.is_empty()).then(|| label.into()),+ };+ *CONTACTS.lock().unwrap() = vec![+ Contact {+ id: "1".into(),+ name: "Sam Rivera".into(),+ numbers: vec![num("+15550100", "Mobile"), num("+15550144", "Work")],+ starred: true,+ photo: None,+ },+ Contact {+ id: "2".into(),+ name: "Alex Chen".into(),+ numbers: vec![num("+15550188", "Mobile")],+ starred: true,+ photo: None,+ },+ Contact {+ id: "3".into(),+ name: "Mom".into(),+ numbers: vec![num("+15550199", "Mobile")],+ starred: true,+ photo: None,+ },+ Contact {+ id: "4".into(),+ name: "City Bakery".into(),+ numbers: vec![num("+15550130", "Work")],+ starred: false,+ photo: None,+ },+ Contact {+ id: "5".into(),+ name: "Jordan Patel".into(),+ numbers: vec![num("+15550155", "Mobile"), num("+15550156", "Home")],+ starred: false,+ photo: None,+ },+ Contact {+ id: "6".into(),+ name: "Priya Nair".into(),+ numbers: vec![num("+15550172", "Mobile")],+ starred: false,+ photo: None,+ },+ ];+}++fn sample_call_log() {+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| d.as_millis() as i64);+ let min = 60_000;+ let entry = |id: &str, number: &str, name: Option<&str>, direction: &str, date: i64, duration: u32| {+ nectarlink_core::CallLogEntry {+ id: id.into(),+ number: number.into(),+ name: name.map(Into::into),+ direction: direction.into(),+ date,+ duration,+ photo: None,+ }+ };+ *CALL_LOG.lock().unwrap() = vec![+ entry("call:1", "+15550100", Some("Sam Rivera"), "missed", now - 18 * min, 0),+ entry("call:2", "+15550188", Some("Alex Chen"), "incoming", now - 2 * 60 * min, 254),+ entry("call:3", "+15550199", Some("Mom"), "outgoing", now - 4 * 60 * min, 612),+ entry("call:4", "+15550123", None, "missed", now - 25 * 60 * min, 0),+ entry("call:5", "+15550155", Some("Jordan Patel"), "outgoing", now - 28 * 60 * min, 95),+ entry("call:6", "+15550190", None, "rejected", now - 30 * 60 * min, 0),+ entry("call:7", "+15550172", Some("Priya Nair"), "incoming", now - 3 * 24 * 60 * min, 180),+ ];+}++fn contact_name_for(number: &str) -> Option<String> {+ let digits: String = number.chars().filter(char::is_ascii_digit).collect();+ CONTACTS.lock().unwrap().iter().find_map(|c| {+ c.numbers+ .iter()+ .any(|n| {+ n.number == number || {+ let nd: String = n.number.chars().filter(char::is_ascii_digit).collect();+ !digits.is_empty() && nd == digits+ }+ })+ .then(|| c.name.clone())+ })+}+/// 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();@@ -753,10 +869,11 @@ impl Platform for TerminalPlatform {let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64);+ let name = contact_name_for(&to[0]).unwrap_or_default();let mut texts = TEXTS.lock().unwrap();let thread = texts.iter().find(|(_, n, ..)| *n == to[0]).map(|(t, ..)| *t);let thread = thread.unwrap_or_else(|| texts.iter().map(|(t, ..)| *t).max().unwrap_or(0) + 1);- texts.push((thread, to[0].clone(), String::new(), false, body.to_owned(), now));+ texts.push((thread, to[0].clone(), name, false, body.to_owned(), now));if let Some(node) = TEXTS_NODE.get().cloned() {tokio::runtime::Handle::current().spawn(async move { node.sms_changed(None).await });}@@ -808,6 +925,87 @@ impl Platform for TerminalPlatform {}Ok(())}+ fn call_log(+ &self,+ before: Option<i64>,+ limit: u32,+ ) -> std::result::Result<Vec<nectarlink_core::CallLogEntry>, String> {+ let mut entries: Vec<nectarlink_core::CallLogEntry> =+ CALL_LOG.lock().unwrap().iter().filter(|e| before.is_none_or(|b| e.date < b)).cloned().collect();+ entries.sort_by_key(|e| std::cmp::Reverse(e.date));+ entries.truncate(limit as usize);+ Ok(entries)+ }+ fn call_dial(&self, number: &str) -> std::result::Result<(), String> {+ println!("A PC started a call to {number}.");+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| d.as_millis() as i64);+ let name = contact_name_for(number);+ let call = nectarlink_core::CallState {+ id: now.to_string(),+ state: "active".into(),+ incoming: false,+ number: Some(number.into()),+ name: name.clone(),+ photo: None,+ missed: false,+ since: Some(now),+ controls: CALL_CONTROLS+ .load(std::sync::atomic::Ordering::Relaxed)+ .then(|| nectarlink_core::CallControls { can_hold: true, ..Default::default() }),+ };+ *CALL.lock().unwrap() = Some(call.clone());+ CALL_LOG.lock().unwrap().push(nectarlink_core::CallLogEntry {+ id: format!("call:{now}"),+ number: number.into(),+ name,+ direction: "outgoing".into(),+ date: now,+ duration: 0,+ photo: None,+ });+ if let Some(node) = CALL_NODE.get().cloned() {+ tokio::runtime::Handle::current().spawn(async move {+ let _ = node.call_changed(call).await;+ node.call_log_changed().await;+ });+ }+ Ok(())+ }+ fn contacts(+ &self,+ query: Option<&str>,+ offset: u32,+ limit: u32,+ ) -> std::result::Result<Vec<nectarlink_core::Contact>, String> {+ let q = query.map(str::trim).filter(|q| !q.is_empty()).map(str::to_lowercase);+ let q_digits: String =+ q.as_deref().map(|s| s.chars().filter(char::is_ascii_digit).collect()).unwrap_or_default();+ let mut items: Vec<nectarlink_core::Contact> = CONTACTS+ .lock()+ .unwrap()+ .iter()+ .filter(|c| match &q {+ None => true,+ Some(q) => {+ c.name.to_lowercase().contains(q)+ || c.numbers.iter().any(|n| {+ n.number.to_lowercase().contains(q)+ || (!q_digits.is_empty()+ && n.number+ .chars()+ .filter(char::is_ascii_digit)+ .collect::<String>()+ .contains(&q_digits))+ })+ }+ })+ .cloned()+ .collect();+ items.sort_by_key(|a| (!a.starred, a.name.to_lowercase()));+ Ok(items.into_iter().skip(offset as usize).take(limit as usize).collect())+ }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.");@@ -885,8 +1083,8 @@ async fn main() -> Result<()> {.with_writer(std::io::stderr).init();- let node = start_node(&cli).await?;- let result = run(&cli, &node).await;+ let node = Box::pin(start_node(&cli)).await?;+ let result = Box::pin(run(&cli, &node)).await;node.shutdown().await;result}@@ -1255,11 +1453,27 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {bail!("texts are on phones: add --as-phone");}sample_texts();+ sample_contacts();+ sample_call_log();let _ = TEXTS_NODE.set(node.clone());+ let _ = CALL_NODE.set(node.clone());+ CALL_CONTROLS.store(true, std::sync::atomic::Ordering::Relaxed);let mut offers = cli.offers.clone();- offers.extend([nectarlink_core::SMS_READ.to_owned(), nectarlink_core::SMS_SEND.to_owned()]);+ offers.extend(+ [+ nectarlink_core::SMS_READ,+ nectarlink_core::SMS_SEND,+ nectarlink_core::CALLS_STATE,+ nectarlink_core::CALLS_CONTROL,+ nectarlink_core::CALLS_IN_CALL,+ nectarlink_core::CALLS_LOG,+ nectarlink_core::CALLS_DIAL,+ nectarlink_core::CONTACTS_READ,+ ]+ .map(str::to_owned),+ );node.update_power(node_power(cli), offers).await;- println!("Sharing sample conversations with paired PCs.");+ println!("Sharing sample conversations, contacts, and calls with paired PCs.");watch(node, false).await?;}Command::IncomingCall { number, caller, basic, answered } => {@@ -1298,6 +1512,8 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {bail!("the demo is a phone: add --as-phone");}sample_texts();+ sample_contacts();+ sample_call_log();let _ = TEXTS_NODE.set(node.clone());let _ = CALL_NODE.set(node.clone());CALL_CONTROLS.store(true, std::sync::atomic::Ordering::Relaxed);@@ -1314,6 +1530,9 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {nectarlink_core::CALLS_STATE,nectarlink_core::CALLS_CONTROL,nectarlink_core::CALLS_IN_CALL,+ nectarlink_core::CALLS_LOG,+ nectarlink_core::CALLS_DIAL,+ nectarlink_core::CONTACTS_READ,].map(str::to_owned),);@@ -1423,6 +1642,68 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {}}}+ Command::Call { device, number, limit } => {+ let mut offers = cli.offers.clone();+ offers.push(nectarlink_core::CALLS_SHOW.into());+ node.update_power(node_power(cli), offers).await;+ let id = resolve(node, device)?;+ wait_until_online(node, id).await?;+ match number {+ Some(number) => {+ node.call_dial(id, number.clone()).await.context("couldn't start the call")?;+ println!("Calling {number}…");+ }+ None => {+ for e in node.call_log(id, None, *limit).await.context("can't read recent calls")? {+ let arrow = match e.direction.as_str() {+ "incoming" => "↙",+ "outgoing" => "↗",+ "missed" => "✕",+ "rejected" => "⊘",+ _ => "•",+ };+ let who = match &e.name {+ Some(n) if !n.is_empty() => format!("{n} ({})", e.number),+ _ => e.number.clone(),+ };+ let dur = if e.duration > 0 {+ format!(" · {}", clock(u64::from(e.duration) * 1000))+ } else {+ String::new()+ };+ println!(+ "{arrow} {} {who}{dur}{}",+ e.direction,+ if e.photo.is_some() { " (photo)" } else { "" }+ );+ }+ }+ }+ }+ Command::Contacts { device, query, offset, limit } => {+ let mut offers = cli.offers.clone();+ offers.push(nectarlink_core::CONTACTS_SHOW.into());+ node.update_power(node_power(cli), offers).await;+ let id = resolve(node, device)?;+ wait_until_online(node, id).await?;+ for c in node.contacts(id, query.clone(), *offset, *limit).await.context("can't list contacts")? {+ let nums: Vec<String> = c+ .numbers+ .iter()+ .map(|n| match &n.label {+ Some(l) if !l.is_empty() => format!("{} ({l})", n.number),+ _ => n.number.clone(),+ })+ .collect();+ println!(+ "{}{} · {}{}",+ if c.starred { "★ " } else { " " },+ c.name,+ nums.join(", "),+ if c.photo.is_some() { " (photo)" } else { "" }+ );+ }+ }Command::Calls { auto, script } => {let mut offers = cli.offers.clone();offers.push(nectarlink_core::CALLS_SHOW.into());@@ -1618,6 +1899,9 @@ async fn pair(node: &Node) -> Result<()> {loop {match events.recv().await {Ok(NodeEvent::Pairing(PairingEvent::Paired(d))) => {+ // Let the pairing close frame flush and the first session+ // connect so both sides record addresses and capabilities.+ let _ = tokio::time::timeout(Duration::from_secs(3), wait_until_online(node, d.id)).await;println!("✓ Paired with {}.", d.info.name);return Ok(());}@@ -1875,6 +2159,8 @@ fn print_event(node: &Node, event: &NodeEvent) {_ => String::new(),},),+ NodeEvent::CallLogChanged { device } => println!("{}: call log changed", name(device)),+ NodeEvent::ContactsChanged { device } => println!("{}: contacts changed", name(device)),NodeEvent::PhotoAdded { device, photo } => println!("{}: new {} {} ({} bytes, preview {} bytes)",name(device),diff --git a/core/nectarlink-core/src/calls.rs b/core/nectarlink-core/src/calls.rsindex ef6ac36..4138d38 100644--- a/core/nectarlink-core/src/calls.rs+++ b/core/nectarlink-core/src/calls.rs@@ -7,7 +7,10 @@ use std::sync::{Arc, Mutex};use nectarlink_protocol::{Envelope, ErrorCode,- messages::{CallAction, CallState, calls, is_dtmf_digit, types},+ messages::{+ CallAction, CallDial, CallLog, CallLogChanged, CallLogEntry, CallLogGet, CallState, calls,+ is_dtmf_digit, types,+ },};use crate::{Error, Result, events::NodeEvent, node::Shared, session::Session};@@ -138,6 +141,13 @@ impl Shared {Ok(())}+ pub(crate) async fn call_log_changed(&self) {+ let Ok(env) = Envelope::new(types::CALL_LOG_CHANGED, &CallLogChanged {}) else { return };+ for session in self.live_sessions().into_iter().filter(|s| self.call_target(s)) {+ let _ = session.send(env.clone()).await;+ }+ }+/// Tells a PC that just connected about the call going on, if any.pub(crate) async fn send_call_state(&self, session: &Arc<Session>) {let Some(call) = self.calls.get() else { return };@@ -164,6 +174,39 @@ pub(crate) async fn command(Ok(())}+pub(crate) async fn log(+ shared: &Shared,+ session: &Session,+ before: Option<i64>,+ limit: u32,+) -> Result<Vec<CallLogEntry>> {+ if !shared.toggle_on(&session.peer, TOGGLE) {+ return Err(Error::Denied);+ }+ let env =+ Envelope::new(types::CALL_LOG, &CallLogGet { before, limit: limit.clamp(1, calls::MAX_LOG_PAGE) })?;+ let CallLog { entries } =+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect_body(types::CALL_LOG)?;+ Ok(entries)+}++pub(crate) async fn dial(shared: &Shared, session: &Session, number: String) -> Result<()> {+ if !shared.toggle_on(&session.peer, TOGGLE) {+ return Err(Error::Denied);+ }+ let dial = CallDial { number: number.trim().to_owned() };+ if !dial.is_valid() {+ return Err(if dial.number.len() > calls::MAX_TEXT_BYTES {+ Error::TooLarge+ } else {+ Error::Protocol("invalid phone number".into())+ });+ }+ let env = Envelope::new(types::CALL_DIAL, &dial)?;+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect(types::OK)?;+ Ok(())+}+/// Handles `call.*`. Returns false for other types.pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {let peer = session.peer;@@ -176,6 +219,14 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &E}Ok(true)}+ types::CALL_LOG_CHANGED => {+ let CallLogChanged {} = env.body()?;+ let shows = shared.local_capabilities().iter().any(|c| c == calls::SHOW);+ if shows && shared.toggle_on(&peer, TOGGLE) {+ shared.emit(NodeEvent::CallLogChanged { device: peer });+ }+ Ok(true)+ }types::CALL_ACTION => {let CallAction { id, action, digit } = env.body()?;let current = shared.calls.get();@@ -209,10 +260,70 @@ 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 => {+ // 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());+ tokio::spawn(async move {+ let reply = answer_log_or_dial(&shared, &session, &env).await.unwrap_or_else(|e| {+ tracing::debug!(error = %e, "bad call request");+ Envelope::error(ErrorCode::BadMessage, "invalid request")+ });+ let _ = session.send(reply.reply_to(env.id)).await;+ });+ Ok(true)+ }_ => Ok(false),}}+async fn answer_log_or_dial(shared: &Arc<Shared>, session: &Session, env: &Envelope) -> Result<Envelope> {+ if !shared.toggle_on(&session.peer, TOGGLE) {+ return Ok(Envelope::error(ErrorCode::Denied, "calls are off for this device"));+ }+ let offers = |cap: &str| shared.local_capabilities().iter().any(|c| c == cap);+ let platform = shared.platform.clone();+ let result = match env.t.as_str() {+ types::CALL_LOG => {+ if !offers(calls::LOG) {+ return Ok(Envelope::error(ErrorCode::Unsupported, "this phone doesn't share recent calls"));+ }+ let CallLogGet { before, limit } = env.body()?;+ let limit = limit.clamp(1, calls::MAX_LOG_PAGE);+ tokio::task::spawn_blocking(move || {+ let mut entries = platform.call_log(before, limit)?;+ for e in &mut entries {+ if e.photo.as_ref().is_some_and(|p| p.len() > calls::MAX_LOG_PHOTO_BYTES) {+ e.photo = None;+ }+ }+ crate::sms::fit(entries, |entries| Envelope::new(types::CALL_LOG, &CallLog { entries }))+ })+ .await+ .unwrap_or_else(|e| Err(e.to_string()))+ }+ _ => {+ if !offers(calls::DIAL) {+ return Ok(Envelope::error(ErrorCode::Unsupported, "this phone doesn't place calls"));+ }+ let dial: CallDial = env.body()?;+ if !dial.is_valid() {+ return Ok(Envelope::error(ErrorCode::BadMessage, "invalid number"));+ }+ let number = dial.number.trim().to_owned();+ tokio::task::spawn_blocking(move || {+ platform.call_dial(&number).map(|()| Envelope::empty(types::OK))+ })+ .await+ .unwrap_or_else(|e| Err(e.to_string()))+ }+ };+ Ok(result.unwrap_or_else(|reason| {+ tracing::warn!(reason, t = env.t, "a call request failed");+ Envelope::error(ErrorCode::Internal, "the phone couldn't do it")+ }))+}+#[cfg(test)]mod tests {use super::*;diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rsindex 5905b09..7fa8873 100644--- a/core/nectarlink-core/src/config.rs+++ b/core/nectarlink-core/src/config.rs@@ -199,6 +199,30 @@ pub trait Platform: Send + Sync + 'static {Err("this device doesn't take calls".into())}+ /// This phone's recent calls before `before` (Unix ms; the latest when+ /// `None`), newest first (a PC asked).+ fn call_log(&self, _before: Option<i64>, _limit: u32) -> Result<Vec<crate::CallLogEntry>, String> {+ Err("this device has no call history".into())+ }++ /// Place a call to `number` (or open the dialer with it filled in) on+ /// this phone (a PC asked; checked not blank).+ fn call_dial(&self, _number: &str) -> Result<(), String> {+ Err("this device doesn't place calls".into())+ }++ /// This phone's contacts matching `query` (or all with phone numbers+ /// when `None`), favorites first then alphabetical, skipping `offset`+ /// (a PC asked).+ fn contacts(+ &self,+ _query: Option<&str>,+ _offset: u32,+ _limit: u32,+ ) -> Result<Vec<crate::Contact>, String> {+ Err("this device has no contacts".into())+ }+/// Run a command on one of this device's media players (a paired device/// asked); `position` is set for [`MediaAction::Seek`].fn media_command(diff --git a/core/nectarlink-core/src/contacts.rs b/core/nectarlink-core/src/contacts.rsnew file mode 100644index 0000000..353a6eb--- /dev/null+++ b/core/nectarlink-core/src/contacts.rs@@ -0,0 +1,122 @@+// SPDX-License-Identifier: MPL-2.0+//! Contacts (docs/protocol/contacts.md): a PC lists and searches a phone's+//! contacts (favorites first, then alphabetical) with their phone numbers and+//! small photos; the phone says when its contacts change.++use std::sync::Arc;++use nectarlink_protocol::{+ DeviceId, Envelope, ErrorCode,+ messages::{Contact, ContactsChanged, ContactsList, ContactsListGet, contacts, types},+};++use crate::{Error, Result, events::NodeEvent, node::Shared, session::Session};++/// The device toggle that allows contacts for a device.+pub(crate) const TOGGLE: &str = "contacts";++impl Shared {+ fn contacts_target(&self, session: &Session) -> bool {+ self.is_desktop(&session.peer)+ && self.toggle_on(&session.peer, TOGGLE)+ && self+ .store+ .get_peer(&session.peer)+ .ok()+ .flatten()+ .is_some_and(|p| p.caps.contains(contacts::SHOW))+ }++ pub(crate) async fn contacts_changed(&self) {+ let Ok(env) = Envelope::new(types::CONTACTS_CHANGED, &ContactsChanged {}) else { return };+ for session in self.live_sessions().into_iter().filter(|s| self.contacts_target(s)) {+ let _ = session.send(env.clone()).await;+ }+ }+}++// ---- A PC asking ----++fn allowed(shared: &Shared, peer: &DeviceId) -> Result<()> {+ if shared.toggle_on(peer, TOGGLE) { Ok(()) } else { Err(Error::Denied) }+}++pub(crate) async fn list(+ shared: &Shared,+ session: &Session,+ query: Option<String>,+ offset: u32,+ limit: u32,+) -> Result<Vec<Contact>> {+ allowed(shared, &session.peer)?;+ let query = query.map(|q| q.trim().to_owned()).filter(|q| !q.is_empty());+ if query.as_ref().is_some_and(|q| q.len() > contacts::MAX_QUERY_BYTES) {+ return Err(Error::TooLarge);+ }+ let env = Envelope::new(+ types::CONTACTS_LIST,+ &ContactsListGet { query, offset, limit: limit.clamp(1, contacts::MAX_PAGE) },+ )?;+ let ContactsList { contacts } =+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect_body(types::CONTACTS_LIST)?;+ Ok(contacts)+}++// ---- The phone answering ----++/// Handles `contacts.*`. Returns false for other types.+pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {+ if env.t == types::CONTACTS_CHANGED {+ let ContactsChanged {} = env.body()?;+ let shows = shared.local_capabilities().iter().any(|c| c == contacts::SHOW);+ if shows && shared.toggle_on(&session.peer, TOGGLE) {+ shared.emit(NodeEvent::ContactsChanged { device: session.peer });+ }+ return Ok(true);+ }+ if env.t != types::CONTACTS_LIST {+ return Ok(false);+ }+ // Querying contacts on the phone takes a moment: not on the session's loop.+ let (shared, session, env) = (shared.clone(), session.clone(), env.clone());+ tokio::spawn(async move {+ let reply = answer(&shared, &session, &env).await.unwrap_or_else(|e| {+ tracing::debug!(error = %e, "bad contacts request");+ Envelope::error(ErrorCode::BadMessage, "invalid request")+ });+ let _ = session.send(reply.reply_to(env.id)).await;+ });+ Ok(true)+}++async fn answer(shared: &Arc<Shared>, session: &Session, env: &Envelope) -> Result<Envelope> {+ if !shared.toggle_on(&session.peer, TOGGLE) {+ return Ok(Envelope::error(ErrorCode::Denied, "contacts are off for this device"));+ }+ if !shared.local_capabilities().iter().any(|c| c == contacts::READ) {+ return Ok(Envelope::error(ErrorCode::Unsupported, "this phone doesn't share contacts"));+ }+ let ContactsListGet { query, offset, limit } = env.body()?;+ if query.as_ref().is_some_and(|q| q.len() > contacts::MAX_QUERY_BYTES) {+ return Ok(Envelope::error(ErrorCode::BadMessage, "query too long"));+ }+ let query = query.map(|q| q.trim().to_owned()).filter(|q| !q.is_empty());+ let limit = limit.clamp(1, contacts::MAX_PAGE);+ let platform = shared.platform.clone();+ let result = tokio::task::spawn_blocking(move || {+ let mut items = platform.contacts(query.as_deref(), offset, limit)?;+ for c in &mut items {+ c.numbers.truncate(contacts::MAX_NUMBERS);+ if c.photo.as_ref().is_some_and(|p| p.len() > contacts::MAX_PHOTO_BYTES) {+ c.photo = None;+ }+ }+ crate::sms::fit(items, |contacts| Envelope::new(types::CONTACTS_LIST, &ContactsList { contacts }))+ })+ .await+ .unwrap_or_else(|e| Err(e.to_string()));+ Ok(result.unwrap_or_else(|reason| {+ tracing::warn!(reason, "a contacts request failed");+ Envelope::error(ErrorCode::Internal, "the phone couldn't read contacts")+ }))+}diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rsindex 4234239..5996a4d 100644--- a/core/nectarlink-core/src/events.rs+++ b/core/nectarlink-core/src/events.rs@@ -139,6 +139,14 @@ pub enum NodeEvent {device: DeviceId,call: crate::CallState,},+ /// A phone's call history changed.+ CallLogChanged {+ device: DeviceId,+ },+ /// A phone's contacts changed.+ ContactsChanged {+ device: DeviceId,+ },/// A phone's screen started or stopped showing here.Mirroring {device: DeviceId,diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rsindex 2437c1d..f082ca7 100644--- a/core/nectarlink-core/src/features.rs+++ b/core/nectarlink-core/src/features.rs@@ -328,6 +328,7 @@ pub const DEVICE_TOGGLES: &[(&str, bool)] = &[("notifications", true),("messages", true),("calls", true),+ ("contacts", true),("clipboard", true),("files", true),("media", true),@@ -611,6 +612,27 @@ pub const FEATURES: &[FeatureDef] = &[],partial: None,},+ FeatureDef {+ id: "calls.log",+ group: FeatureGroup::Calls,+ requires: &[phone("call.log", Unlock::Permission(Permission::Phone)), DeviceToggle("calls")],+ partial: None,+ },+ FeatureDef {+ id: "calls.dial",+ group: FeatureGroup::Calls,+ requires: &[phone("call.dial", Unlock::Permission(Permission::Phone)), DeviceToggle("calls")],+ partial: None,+ },+ FeatureDef {+ id: "contacts.read",+ group: FeatureGroup::Calls,+ requires: &[+ phone("contacts.read", Unlock::Permission(Permission::Contacts)),+ DeviceToggle("contacts"),+ ],+ partial: None,+ },// ClipboardFeatureDef {id: "clipboard.pc_to_phone",@@ -772,6 +794,9 @@ mod tests {"sms.read","sms.send","call.state",+ "call.log",+ "call.dial",+ "contacts.read","clip.write","clip.share","files.transfer",diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsindex 0e9b390..33629db 100644--- a/core/nectarlink-core/src/lib.rs+++ b/core/nectarlink-core/src/lib.rs@@ -10,6 +10,7 @@ mod actions;mod calls;mod clipboard;mod config;+mod contacts;mod error;mod events;pub mod features;@@ -42,12 +43,15 @@ pub use nectarlink_protocol::messages::clip::{pub use nectarlink_protocol::{DeviceId, PacketKind,messages::{- Battery, CLIP_MAX_BYTES, CallControls, CallState, DeviceInfo, DeviceKind, MediaPlayer,- MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorStart, Notification, NotificationAction,- PhoneApp, PhotoNew as Photo, PowerLevel, SmsMessage, SmsPart, SmsThread, TouchAction,+ Battery, CLIP_MAX_BYTES, CallControls, CallLogEntry, CallState, Contact, ContactNumber, DeviceInfo,+ DeviceKind, MediaPlayer, MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorStart, Notification,+ NotificationAction, PhoneApp, 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,+ 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,},+ contacts::{READ as CONTACTS_READ, SHOW as CONTACTS_SHOW},is_package_name,mirror::{AUDIO as MIRROR_AUDIO, AUDIO_PLAYBACK as MIRROR_AUDIO_PLAYBACK, CAPTURE as MIRROR_CAPTURE,diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rsindex 6f1f993..1c6b029 100644--- a/core/nectarlink-core/src/node.rs+++ b/core/nectarlink-core/src/node.rs@@ -1035,6 +1035,50 @@ impl Node {crate::calls::command(&self.shared, &session, id, command).await}+ /// This phone's call history changed: connected PCs that show it catch up.+ pub async fn call_log_changed(&self) {+ self.shared.call_log_changed().await;+ }++ /// A paired phone's recent calls before `before` (Unix ms; the latest+ /// when `None`), newest first.+ pub async fn call_log(+ &self,+ peer: DeviceId,+ before: Option<i64>,+ limit: u32,+ ) -> Result<Vec<crate::CallLogEntry>> {+ let session = self.connected(&peer)?;+ crate::calls::log(&self.shared, &session, before, limit).await+ }++ /// 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<()> {+ let session = self.connected(&peer)?;+ crate::calls::dial(&self.shared, &session, number).await+ }++ // ---- Contacts (docs/protocol/contacts.md) ----++ /// This phone's contacts changed: connected PCs that show them catch up.+ pub async fn contacts_changed(&self) {+ self.shared.contacts_changed().await;+ }++ /// Lists or searches a paired phone's contacts (favorites first, then+ /// alphabetical), skipping `offset`.+ pub async fn contacts(+ &self,+ peer: DeviceId,+ query: Option<String>,+ offset: u32,+ limit: u32,+ ) -> Result<Vec<crate::Contact>> {+ let session = self.connected(&peer)?;+ crate::contacts::list(&self.shared, &session, query, offset, limit).await+ }+// ---- Photos (docs/protocol/photos.md) ----/// A photo or screenshot just appeared on this phone; announced to everydiff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rsindex 2b8da35..aa66b2e 100644--- a/core/nectarlink-core/src/session.rs+++ b/core/nectarlink-core/src/session.rs@@ -383,6 +383,7 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->t if t.starts_with("clip.") && crate::clipboard::handle(shared, session, &env).await? => {}t if t.starts_with("photos.") && crate::photos::handle(shared, session, &env).await? => {}t if t.starts_with("call.") && crate::calls::handle(shared, session, &env).await? => {}+ t if t.starts_with("contacts.") && crate::contacts::handle(shared, session, &env).await? => {}t if t.starts_with("sms.") && crate::sms::handle(shared, session, &env).await? => {}t if t.starts_with("mirror.") && crate::mirror::handle(shared, session, &env).await? => {}other => {diff --git a/core/nectarlink-core/src/sms.rs b/core/nectarlink-core/src/sms.rsindex ea2035c..11a8a76 100644--- a/core/nectarlink-core/src/sms.rs+++ b/core/nectarlink-core/src/sms.rs@@ -183,7 +183,7 @@ async fn answer(shared: &Arc<Shared>, session: &Session, env: &Envelope) -> Resu}/// The envelope for as many of `items` (newest first) as fit in a frame.-fn fit<T: Clone>(+pub(crate) fn fit<T: Clone>(mut items: Vec<T>,wrap: impl Fn(Vec<T>) -> std::result::Result<Envelope, nectarlink_protocol::ProtocolError>,) -> std::result::Result<Envelope, String> {diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex 0dba41c..4f307c7 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -31,6 +31,7 @@ struct RecordingPlatform {power: Mutex<Vec<PowerAction>>,links: Mutex<Vec<String>>,calls: Mutex<Vec<(String, nectarlink_core::CallCommand)>>,+ dialed: Mutex<Vec<String>>,texts: Mutex<Vec<(Vec<String>, String)>>,mirror_asks: Mutex<Vec<String>>,/// What a PC got of a phone's screen.@@ -169,6 +170,90 @@ impl Platform for RecordingPlatform {self.calls.lock().unwrap().push((id.to_owned(), command));Ok(())}+ fn call_log(+ &self,+ before: Option<i64>,+ limit: u32,+ ) -> Result<Vec<nectarlink_core::CallLogEntry>, String> {+ let entry = |date: i64| nectarlink_core::CallLogEntry {+ id: format!("log:{date}"),+ number: format!("+1555010{date}"),+ name: (date % 2 == 0).then(|| format!("Caller {date}")),+ direction: match date % 4 {+ 0 => "incoming",+ 1 => "outgoing",+ 2 => "missed",+ _ => "rejected",+ }+ .into(),+ date,+ duration: if date % 2 == 0 { 42 } else { 0 },+ // Entry 3 has an oversized photo that the core should drop.+ photo: match date {+ 4 => Some(vec![0xff, 0xd8]),+ 3 => Some(vec![0; 20 * 1024]),+ _ => None,+ },+ };+ let newest = before.unwrap_or(5);+ Ok((0..newest).rev().take(limit as usize).map(entry).collect())+ }+ fn call_dial(&self, number: &str) -> Result<(), String> {+ self.dialed.lock().unwrap().push(number.to_owned());+ Ok(())+ }+ fn contacts(+ &self,+ query: Option<&str>,+ offset: u32,+ limit: u32,+ ) -> Result<Vec<nectarlink_core::Contact>, String> {+ use nectarlink_core::{Contact, ContactNumber};+ let all = vec![+ Contact {+ id: "c1".into(),+ name: "Sam Rivera".into(),+ numbers: vec![ContactNumber { number: "+15550100".into(), label: Some("Mobile".into()) }],+ starred: true,+ photo: Some(vec![0xff, 0xd8]),+ },+ Contact {+ id: "c2".into(),+ name: "Alex Chen".into(),+ numbers: vec![ContactNumber { number: "+15550188".into(), label: Some("Mobile".into()) }],+ starred: true,+ // Oversized photo: should be dropped by core rather than dropping the contact.+ photo: Some(vec![0; 20 * 1024]),+ },+ Contact {+ id: "c3".into(),+ name: "Jordan Patel".into(),+ numbers: vec![ContactNumber { number: "+15550155".into(), label: Some("Work".into()) }],+ starred: false,+ photo: None,+ },+ Contact {+ id: "c4".into(),+ name: "Priya Nair".into(),+ numbers: vec![ContactNumber { number: "+15550172".into(), label: None }],+ starred: false,+ photo: None,+ },+ ];+ let q = query.map(str::to_lowercase);+ Ok(all+ .into_iter()+ .filter(|c| match &q {+ None => true,+ Some(q) => {+ c.name.to_lowercase().contains(q)+ || c.numbers.iter().any(|n| n.number.to_lowercase().contains(q))+ }+ })+ .skip(offset as usize)+ .take(limit as usize)+ .collect())+ }fn open_photo(&self, id: &str) -> Result<OutgoingFile, String> {let barrier = self.photo_barrier.lock().unwrap().clone();if let Some(barrier) = barrier {@@ -1623,3 +1708,116 @@ async fn slow_rpc_does_not_block_control_stream() {let transfer_id = with_timeout("photos.get finishes", get_task).await.unwrap().expect("photo sent");wait_transfer(&mut pc, &transfer_id, "photo received", saved).await;}++#[tokio::test(flavor = "multi_thread")]+async fn call_log_and_dial_work_and_respect_permissions_and_toggles() {+ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[nectarlink_core::CALLS_SHOW]).await;+ let mut phone = device_with("Pixel", DeviceKind::Phone, &[nectarlink_core::CALLS_LOG]).await;+ pair_qr(&mut pc, &mut phone).await;+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());++ let page1 = with_timeout("call log page 1", pc.node.call_log(phone_id, None, 3)).await.unwrap();+ assert_eq!(page1.len(), 3);+ assert_eq!((&*page1[0].id, &*page1[0].direction, page1[0].date), ("log:4", "incoming", 4));+ assert_eq!(page1[0].photo.as_deref(), Some(&[0xff, 0xd8][..]));+ // Entry 3 had an oversized photo: kept without its photo.+ assert_eq!((&*page1[1].id, &*page1[1].direction, page1[1].photo.as_ref()), ("log:3", "rejected", None));+ assert_eq!((&*page1[2].id, &*page1[2].direction), ("log:2", "missed"));++ let page2 = with_timeout("call log page 2", pc.node.call_log(phone_id, Some(2), 3)).await.unwrap();+ assert_eq!(page2.iter().map(|e| e.date).collect::<Vec<_>>(), [1, 0]);++ phone.node.call_log_changed().await;+ wait_for(&mut pc, "call log changed", |e| match e {+ NodeEvent::CallLogChanged { device } if *device == phone_id => Some(()),+ _ => None,+ })+ .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)));++ phone+ .node+ .update_power(+ PowerLevel::NotApplicable,+ vec![+ "media.control".into(),+ nectarlink_core::CALLS_LOG.into(),+ nectarlink_core::CALLS_DIAL.into(),+ ],+ )+ .await;+ wait_for(&mut pc, "call.dial unlocked", |e| match e {+ NodeEvent::Capabilities(m)+ if m.device == phone_id && m.state("calls.dial") == Some(FeatureState::Available) =>+ {+ Some(())+ }+ _ => None,+ })+ .await;++ with_timeout("dial", pc.node.call_dial(phone_id, "+15550100".into())).await.unwrap();+ assert_eq!(*phone.platform.dialed.lock().unwrap(), ["+15550100"]);++ // 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)));+}++#[tokio::test(flavor = "multi_thread")]+async fn contacts_list_search_page_and_respect_permissions_and_toggles() {+ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[nectarlink_core::CONTACTS_SHOW]).await;+ let mut phone = device_with("Pixel", DeviceKind::Phone, &[]).await;+ pair_qr(&mut pc, &mut phone).await;+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());++ // Without `contacts.read` on the phone, listing contacts is unsupported.+ assert!(matches!(pc.node.contacts(phone_id, None, 0, 10).await, Err(Error::Unsupported)));++ phone+ .node+ .update_power(+ PowerLevel::NotApplicable,+ vec!["media.control".into(), nectarlink_core::CONTACTS_READ.into()],+ )+ .await;+ wait_for(&mut pc, "contacts.read unlocked", |e| match e {+ NodeEvent::Capabilities(m)+ if m.device == phone_id && m.state("contacts.read") == Some(FeatureState::Available) =>+ {+ Some(())+ }+ _ => None,+ })+ .await;++ let first_two = with_timeout("contacts page 1", pc.node.contacts(phone_id, None, 0, 2)).await.unwrap();+ assert_eq!(first_two.len(), 2);+ assert_eq!((&*first_two[0].name, first_two[0].starred), ("Sam Rivera", true));+ assert_eq!(first_two[0].photo.as_deref(), Some(&[0xff, 0xd8][..]));+ // Oversized photo on c2 was stripped rather than dropping the contact.+ assert_eq!((&*first_two[1].name, first_two[1].photo.as_ref()), ("Alex Chen", None));++ let rest = with_timeout("contacts page 2", pc.node.contacts(phone_id, None, 2, 10)).await.unwrap();+ assert_eq!(rest.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["Jordan Patel", "Priya Nair"]);++ let searched = with_timeout("contacts search", pc.node.contacts(phone_id, Some("patel".into()), 0, 10))+ .await+ .unwrap();+ assert_eq!(searched.len(), 1);+ assert_eq!(searched[0].name, "Jordan Patel");++ phone.node.contacts_changed().await;+ wait_for(&mut pc, "contacts changed", |e| match e {+ NodeEvent::ContactsChanged { device } if *device == phone_id => Some(()),+ _ => None,+ })+ .await;++ // Turning `contacts` off for this PC refuses contact queries.+ phone.node.set_device_toggle(pc_id, "contacts", false).unwrap();+ assert!(matches!(pc.node.contacts(phone_id, None, 0, 10).await, Err(Error::Denied)));+}diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex db136a3..b7214cb 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -434,6 +434,14 @@ pub enum Event {id: String,call_id: String,},+ /// A paired phone's call history changed (PCs only).+ CallLogChanged {+ id: String,+ },+ /// A paired phone's contacts changed (PCs only).+ ContactsChanged {+ id: String,+ },/// A paired phone's screen (session 0) or app window started or/// stopped showing (PCs only).Mirroring {@@ -663,7 +671,43 @@ macro_rules! private_debug {})*};}-private_debug!(SmsThread, SmsMessage, SmsPartData);+private_debug!(SmsThread, SmsMessage, SmsPartData, CallLogEntry, ContactNumber, Contact);++/// One call in this phone's call history (docs/protocol/calls.md).+#[derive(Clone, PartialEq, Eq, uniffi::Record)]+pub struct CallLogEntry {+ pub id: String,+ /// Who called, or who was called ("" when withheld).+ pub number: String,+ /// The contact's name, when the number is a contact.+ pub name: Option<String>,+ /// "incoming", "outgoing", "missed" or "rejected".+ pub direction: String,+ /// Unix milliseconds.+ pub date: i64,+ /// Seconds on the call (0 when missed or not answered).+ pub duration: u32,+ /// The contact's photo: a JPEG of at most 16 KB.+ pub photo: Option<Vec<u8>>,+}++/// One phone number on a contact (docs/protocol/contacts.md).+#[derive(Clone, PartialEq, Eq, uniffi::Record)]+pub struct ContactNumber {+ pub number: String,+ pub label: Option<String>,+}++/// A contact on this phone (docs/protocol/contacts.md).+#[derive(Clone, PartialEq, Eq, uniffi::Record)]+pub struct Contact {+ pub id: String,+ pub name: String,+ pub numbers: Vec<ContactNumber>,+ pub starred: bool,+ /// A JPEG of at most 16 KB.+ pub photo: Option<Vec<u8>>,+}/// A call on this phone (docs/protocol/calls.md).#[derive(Clone, PartialEq, Eq, uniffi::Record)]@@ -1130,6 +1174,8 @@ impl From<NodeEvent> for Event {NodeEvent::Call { device, call } => {Event::CallChanged { id: device.to_string(), call_id: call.id }}+ NodeEvent::CallLogChanged { device } => Event::CallLogChanged { id: device.to_string() },+ NodeEvent::ContactsChanged { device } => Event::ContactsChanged { id: device.to_string() },NodeEvent::SmsChanged { device, thread } => Event::SmsChanged { id: device.to_string(), thread },NodeEvent::Mirroring { device, session, on } => {Event::Mirroring { id: device.to_string(), session, on }@@ -1243,6 +1289,15 @@ pub trait Platform: Send + Sync {/// A PC asked to answer, decline or silence call `id` (the call in/// progress). False if the phone couldn't.fn call_command(&self, id: String, command: CallCommand) -> bool;+ /// A PC asked for recent calls before `before` (Unix ms; the latest when+ /// null), newest first.+ fn call_log(&self, before: Option<i64>, limit: u32) -> Vec<CallLogEntry>;+ /// 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 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>;/// A PC asked for this phone's screen (and, with `audio`, its sound):/// ask the user (then call `mirror_open`, and `mirror_open_audio` for/// the sound). With `app` (and a `session` other than 0): run that app@@ -1424,6 +1479,43 @@ impl core::Platform for PlatformAdapter {};if self.0.call_command(id.to_owned(), command) { Ok(()) } else { Err("the phone couldn't".into()) }}+ fn call_log(&self, before: Option<i64>, limit: u32) -> Result<Vec<core::CallLogEntry>, String> {+ Ok(self+ .0+ .call_log(before, limit)+ .into_iter()+ .map(|e| core::CallLogEntry {+ id: e.id,+ number: e.number,+ name: e.name,+ direction: e.direction,+ date: e.date,+ duration: e.duration,+ photo: e.photo,+ })+ .collect())+ }+ 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 contacts(&self, query: Option<&str>, offset: u32, limit: u32) -> Result<Vec<core::Contact>, String> {+ Ok(self+ .0+ .contacts(query.map(str::to_owned), offset, limit)+ .into_iter()+ .map(|c| core::Contact {+ id: c.id,+ name: c.name,+ numbers: c+ .numbers+ .into_iter()+ .map(|n| core::ContactNumber { number: n.number, label: n.label })+ .collect(),+ starred: c.starred,+ photo: c.photo,+ })+ .collect())+ }fn open_photo(&self, id: &str) -> Result<core::OutgoingFile, String> {let file = self.0.open_photo(id.to_owned()).ok_or("it's gone")?;file_to_send(file).map_err(|e| e.to_string())@@ -1746,6 +1838,18 @@ impl NectarlinkNode {self.run(async move { node.sms_changed(thread).await }).await;}+ /// This phone's call history changed: PCs that show it catch up.+ pub async fn call_log_changed(&self) {+ let node = self.node.clone();+ self.run(async move { node.call_log_changed().await }).await;+ }++ /// This phone's contacts changed: PCs that show them catch up.+ pub async fn contacts_changed(&self) {+ let node = self.node.clone();+ self.run(async move { node.contacts_changed().await }).await;+ }+/// A call on this phone rang, was answered or ended: tells the PCs that/// show calls (and are allowed them), now and when they connect during it.pub async fn call_changed(&self, call: Call) -> Result<()> {diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex 3552f95..862bd2f 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -45,6 +45,11 @@ pub mod types {pub const PHOTOS_SENDING: &str = "photos.sending";pub const CALL_STATE: &str = "call.state";pub const CALL_ACTION: &str = "call.action";+ 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 CONTACTS_LIST: &str = "contacts.list";+ pub const CONTACTS_CHANGED: &str = "contacts.changed";pub const SMS_THREADS: &str = "sms.threads";pub const SMS_MESSAGES: &str = "sms.messages";pub const SMS_SEND: &str = "sms.send";@@ -922,8 +927,16 @@ pub mod calls {/// Offered by phones that control a call in progress (mute, speaker,/// hold, keypad) when a PC asks.pub const IN_CALL: &str = "call.incall";+ /// Offered by phones that list recent calls from the call log.+ 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";/// 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.+ pub const MAX_LOG_PHOTO_BYTES: usize = 16 * 1024;+ /// Most call log entries in one answer.+ pub const MAX_LOG_PAGE: u32 = 100;pub const MAX_ID_BYTES: usize = 64;pub const MAX_TEXT_BYTES: usize = 256;@@ -931,6 +944,11 @@ pub mod calls {pub const ACTIVE: &str = "active";pub const ENDED: &str = "ended";+ pub const DIR_INCOMING: &str = "incoming";+ pub const DIR_OUTGOING: &str = "outgoing";+ pub const DIR_MISSED: &str = "missed";+ pub const DIR_REJECTED: &str = "rejected";+pub const ANSWER: &str = "answer";pub const DECLINE: &str = "decline";pub const SILENCE: &str = "silence";@@ -1034,6 +1052,170 @@ pub fn is_dtmf_digit(digit: &str) -> bool {digit.len() == 1 && digit.chars().all(|c| c.is_ascii_digit() || c == '*' || c == '#')}+/// One call in the phone's call history (`call.log`).+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct CallLogEntry {+ pub id: String,+ /// Who called, or who was called (empty when withheld).+ #[serde(default)]+ pub number: String,+ /// The contact's name, when the number is a contact.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ /// `incoming`, `outgoing`, `missed` or `rejected`.+ pub direction: String,+ /// When the call started, in Unix milliseconds.+ pub date: i64,+ /// Seconds on the call (`0` when missed or not answered).+ #[serde(default)]+ pub duration: u32,+ /// The contact's photo (JPEG, at most 16 KiB).+ #[serde(default, skip_serializing_if = "Option::is_none", with = "serde_bytes")]+ pub photo: Option<Vec<u8>>,+}++/// Never prints the number, name or photo (protocol v0 §11).+impl std::fmt::Debug for CallLogEntry {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("CallLogEntry")+ .field("id", &self.id)+ .field("direction", &self.direction)+ .field("duration", &self.duration)+ .finish_non_exhaustive()+ }+}++/// Body of `call.log`: recent calls before `before` (Unix milliseconds; the+/// latest when missing), newest first.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct CallLogGet {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub before: Option<i64>,+ pub limit: u32,+}++/// Answer to `call.log`.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct CallLog {+ pub entries: Vec<CallLogEntry>,+}++/// Body of `call.log.changed`.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct CallLogChanged {}++/// Body of `call.dial`: ask the phone to call `number`.+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct CallDial {+ pub number: 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()+ }+}++impl CallDial {+ pub fn is_valid(&self) -> bool {+ !self.number.trim().is_empty() && self.number.len() <= calls::MAX_TEXT_BYTES+ }+}++// ---- Contacts (docs/protocol/contacts.md) ----++pub mod contacts {+ /// Offered by phones that share their contacts.+ pub const READ: &str = "contacts.read";+ /// Offered by PCs that show contacts.+ pub const SHOW: &str = "contacts.show";+ /// Most contacts in one answer.+ pub const MAX_PAGE: u32 = 200;+ /// A search query: at most this many bytes.+ pub const MAX_QUERY_BYTES: usize = 256;+ /// Most phone numbers on one contact.+ pub const MAX_NUMBERS: usize = 16;+ /// A contact's photo: a JPEG of at most this many bytes.+ pub const MAX_PHOTO_BYTES: usize = 16 * 1024;+}++/// One phone number on a contact.+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct ContactNumber {+ pub number: String,+ /// Optional type/label, e.g. `"mobile"`, `"home"`, `"work"`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub label: Option<String>,+}++/// Never prints the number or label (protocol v0 §11).+impl std::fmt::Debug for ContactNumber {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("ContactNumber").finish_non_exhaustive()+ }+}++/// A contact on the phone (`contacts.list`).+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Contact {+ pub id: String,+ pub name: String,+ pub numbers: Vec<ContactNumber>,+ /// Favorite / starred on the phone.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub starred: bool,+ /// Small JPEG thumbnail (at most 16 KiB).+ #[serde(default, skip_serializing_if = "Option::is_none", with = "serde_bytes")]+ pub photo: Option<Vec<u8>>,+}++/// Never prints the name, numbers or photo (protocol v0 §11).+impl std::fmt::Debug for Contact {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Contact")+ .field("id", &self.id)+ .field("numbers", &self.numbers.len())+ .field("starred", &self.starred)+ .finish_non_exhaustive()+ }+}++/// Body of `contacts.list` request.+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct ContactsListGet {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub query: Option<String>,+ #[serde(default, skip_serializing_if = "is_zero")]+ pub offset: u32,+ pub limit: u32,+}++fn is_zero(n: &u32) -> bool {+ *n == 0+}++/// Never prints the search query (protocol v0 §11).+impl std::fmt::Debug for ContactsListGet {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("ContactsListGet")+ .field("has_query", &self.query.is_some())+ .field("offset", &self.offset)+ .field("limit", &self.limit)+ .finish()+ }+}++/// Answer to `contacts.list`.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct ContactsList {+ pub contacts: Vec<Contact>,+}++/// Body of `contacts.changed`.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct ContactsChanged {}+// ---- Photos (docs/protocol/photos.md) ----pub mod photos {@@ -1495,4 +1677,42 @@ mod tests {let env = Envelope::new("x", &PowerLevel::NotApplicable).unwrap();assert_eq!(env.b, Some(ciborium::Value::Text("n/a".into())));}++ #[test]+ fn call_log_dial_and_contacts_round_trip_and_hide_private_fields() {+ let dial = CallDial { number: "+1 555 0100".into() };+ 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());++ let entry = CallLogEntry {+ id: "10".into(),+ number: "+15550100".into(),+ name: Some("Ada Lovelace".into()),+ direction: calls::DIR_MISSED.into(),+ date: 1_760_000_000_000,+ duration: 0,+ photo: Some(vec![0xff, 0xd8]),+ };+ assert!(!format!("{entry:?}").contains("555") && !format!("{entry:?}").contains("Ada"));+ let env = Envelope::new(types::CALL_LOG, &CallLog { entries: vec![entry.clone()] }).unwrap();+ let back: CallLog = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();+ assert_eq!(back.entries, vec![entry]);++ let contact = Contact {+ id: "42".into(),+ name: "Ada Lovelace".into(),+ numbers: vec![ContactNumber { number: "+15550100".into(), label: Some("mobile".into()) }],+ starred: true,+ photo: Some(vec![0xff, 0xd8]),+ };+ assert!(!format!("{contact:?}").contains("Ada") && !format!("{contact:?}").contains("555"));+ let get = ContactsListGet { query: Some("Ada".into()), offset: 0, limit: 50 };+ assert!(!format!("{get:?}").contains("Ada"));+ let env =+ Envelope::new(types::CONTACTS_LIST, &ContactsList { contacts: vec![contact.clone()] }).unwrap();+ let back: ContactsList = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();+ assert_eq!(back.contacts, vec![contact]);+ }}diff --git a/desktop/app/build.rs b/desktop/app/build.rsindex 929e47e..5559c9a 100644--- a/desktop/app/build.rs+++ b/desktop/app/build.rs@@ -47,6 +47,7 @@ const QML: &[&str] = &["qml/components/Toggle.qml","qml/components/TransferItem.qml","qml/components/Txt.qml",+ "qml/pages/CallsPage.qml","qml/pages/HomePage.qml","qml/pages/MessagesPage.qml","qml/pages/PairingPanel.qml",diff --git a/desktop/app/qml/Icons.qml b/desktop/app/qml/Icons.qmlindex c77f2a5..4262dff 100644--- a/desktop/app/qml/Icons.qml+++ b/desktop/app/qml/Icons.qml@@ -33,7 +33,13 @@ QtObject {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 call: "M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2z"+ readonly property string callIncoming: "M17 7L7 17M7 9v8h8"+ readonly property string callOutgoing: "M7 17L17 7M9 7h8v8"+ readonly property string callMissed: "M3 8l6 6 5-5 7 7M3 14V8h6"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 star: "M12 3l2.8 5.7 6.2.9-4.5 4.4 1.1 6.2L12 17.3 6.4 20.2l1.1-6.2L3 9.6l6.2-.9z"+ readonly property string backspace: "M21 6H9l-6 6 6 6h12a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1zM16 10l-4 4M12 10l4 4"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/MainWindow.qml b/desktop/app/qml/MainWindow.qmlindex 55e18ea..14b95b5 100644--- a/desktop/app/qml/MainWindow.qml+++ b/desktop/app/qml/MainWindow.qml@@ -116,6 +116,12 @@ NativeWindow {selected: window.page === "messages"onClicked: window.page = "messages"}+ NavItem {+ iconPath: Icons.call+ text: qsTr("Calls")+ selected: window.page === "calls"+ onClicked: window.page = "calls"+ }NavItem {iconPath: Icons.settingstext: qsTr("Settings")@@ -153,7 +159,9 @@ NativeWindow {anchors.leftMargin: Theme.contentPaddinganchors.verticalCenter: parent.verticalCentertext: window.page === "home" ? qsTr("Home")- : window.page === "messages" ? qsTr("Messages") : qsTr("Settings")+ : window.page === "messages" ? qsTr("Messages")+ : window.page === "calls" ? qsTr("Calls")+ : qsTr("Settings")role: "headline"size: 20}@@ -202,6 +210,16 @@ NativeWindow {deviceId: homePage.currentDeviceIddeviceName: homePage.currentDeviceName}+ CallsPage {+ anchors.fill: parent+ active: window.page === "calls"+ deviceId: homePage.currentDeviceId+ deviceName: homePage.currentDeviceName+ onTextRequested: (number, name) => {+ Messages.startChat(homePage.currentDeviceId, number, name)+ window.page = "messages"+ }+ }SettingsPage {anchors.fill: parentactive: window.page === "settings"diff --git a/desktop/app/qml/pages/CallsPage.qml b/desktop/app/qml/pages/CallsPage.qmlnew file mode 100644index 0000000..407b63e--- /dev/null+++ b/desktop/app/qml/pages/CallsPage.qml@@ -0,0 +1,1109 @@+// SPDX-License-Identifier: GPL-3.0-or-later+import QtQuick+import app.nectarlink++// Calls: recent calls and contacts on the left, the active call and a+// keypad dialer on the right. Audio stays on the phone; calls and texts+// started here go through the phone.+Item {+ id: page+ property bool active: false+ // The phone shown (the one on Home).+ property string deviceId+ property string deviceName+ // "recent" (call log) or "contacts".+ property string tab: "recent"+ // Contact shown above the keypad when picked from the list.+ property var selectedContact: null++ signal textRequested(string number, string name)++ readonly property var callLog: { try { return JSON.parse(PhoneCall.callLog) } catch (e) { return [] } }+ readonly property var contacts: { try { return JSON.parse(PhoneCall.contacts) } catch (e) { return [] } }+ readonly property string query: search.text.trim().toLocaleLowerCase()++ readonly property var shownCalls: query.length === 0 ? callLog+ : callLog.filter(c => ((c.name || "") + " " + c.number).toLocaleLowerCase().indexOf(query) >= 0)++ readonly property var shownContacts: query.length === 0 ? contacts+ : contacts.filter(c => {+ const nums = (c.numbers || []).map(n => n.number + " " + (n.label || "")).join(" ")+ return (c.name + " " + nums).toLocaleLowerCase().indexOf(query) >= 0+ })++ // Digits for matching a typed number to a contact.+ function digits(s) {+ const d = (s || "").replace(/\D/g, "")+ return d.length > 9 ? d.slice(d.length - 9) : d+ }++ // Contact matching the number currently in the dialer, if any.+ readonly property var dialMatchedContact: {+ const d = digits(dialInput.text)+ if (d.length < 3) return null+ for (let i = 0; i < contacts.length; i++) {+ const c = contacts[i]+ const nums = c.numbers || []+ for (let j = 0; j < nums.length; j++) {+ if (digits(nums[j].number) === d)+ return { name: c.name, label: nums[j].label || "" }+ }+ }+ return null+ }++ // A stable color for a contact (in Bloom).+ function hueOf(name) {+ let h = 0+ for (let i = 0; i < name.length; i++)+ h = (h * 31 + name.charCodeAt(i)) % 360+ return h / 360+ }++ // "Today", "Yesterday", or the date, for call log separators.+ function dayLabel(ms) {+ const date = new Date(ms)+ const today = new Date()+ const yesterday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1)+ if (date.toDateString() === today.toDateString()) return qsTr("Today")+ if (date.toDateString() === yesterday.toDateString()) return qsTr("Yesterday")+ return date.toLocaleDateString(Qt.locale(), date.getFullYear() === today.getFullYear() ? "dddd, d MMMM" : Locale.LongFormat)+ }++ // "14:05", "Yesterday", "Tue", or a date.+ function shortTime(ms) {+ const date = new Date(ms)+ const now = new Date()+ if (date.toDateString() === now.toDateString())+ return date.toLocaleTimeString(Qt.locale(), Locale.ShortFormat)+ const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)+ if (date.toDateString() === yesterday.toDateString())+ return qsTr("Yesterday")+ if (now - date < 6 * 24 * 3600 * 1000)+ return date.toLocaleDateString(Qt.locale(), "ddd")+ return date.toLocaleDateString(Qt.locale(), Locale.ShortFormat)+ }++ // "1:05" or "42s" for a completed call's duration.+ function formatDuration(seconds) {+ if (!seconds || seconds <= 0) return ""+ const h = Math.floor(seconds / 3600)+ const m = Math.floor((seconds % 3600) / 60)+ const s = seconds % 60+ if (h > 0)+ return h + ":" + String(m).padStart(2, "0") + ":" + String(s).padStart(2, "0")+ if (m > 0)+ return m + ":" + String(s).padStart(2, "0")+ return qsTr("%1s").arg(s)+ }++ function placeCall(number) {+ const n = (number || "").trim()+ if (n.length === 0 || !PhoneCall.canDial || PhoneCall.dialing)+ return+ PhoneCall.dial(n)+ }++ function startText(number, name) {+ const n = (number || "").trim()+ if (n.length === 0)+ return+ page.textRequested(n, name || "")+ }++ function load() {+ if (active && deviceId.length > 0)+ PhoneCall.open(deviceId)+ }++ onActiveChanged: if (active) load()+ onDeviceIdChanged: {+ selectedContact = null+ load()+ }++ opacity: active ? 1 : 0+ visible: opacity > 0+ Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }+ transform: Translate {+ y: page.active || Theme.reduceMotion ? 0 : 12+ Behavior on y { SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }+ }++ Shortcut {+ sequence: StandardKey.Find+ enabled: page.active && page.deviceId.length > 0+ onActivated: search.forceActiveFocus()+ }+ Shortcut {+ sequence: "Esc"+ enabled: page.active && (page.selectedContact !== null || search.text.length > 0)+ onActivated: {+ if (search.text.length > 0)+ search.text = ""+ else+ page.selectedContact = null+ }+ }++ readonly property bool phoneOffline: page.deviceId.length === 0+ || (PhoneCall.logStatus === "offline" && PhoneCall.contactsStatus === "offline"+ && page.callLog.length === 0 && page.contacts.length === 0)++ // ---- No phone paired, or phone offline with nothing cached ----+ Column {+ anchors.centerIn: parent+ width: Math.min(parent.width - Theme.contentPadding * 2, 420)+ spacing: 12+ visible: page.phoneOffline+ Icon {+ anchors.horizontalCenter: parent.horizontalCenter+ width: 40; height: 40+ stroke: 1.5+ path: Icons.call+ color: Theme.surfaceContentVariant+ }+ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ role: "title"+ text: page.deviceId.length === 0 ? qsTr("Call from your PC")+ : qsTr("%1 isn't connected").arg(page.deviceName)+ }+ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.WordWrap+ role: "body"+ muted: true+ text: page.deviceId.length === 0 ? qsTr("Pair your phone to see recent calls, browse contacts, and place calls here.")+ : qsTr("Your call log and contacts show up here when it's back.")+ }+ }++ // ---- Left pane: Recent calls and Contacts ----+ Item {+ id: list+ visible: !page.phoneOffline+ width: Math.min(370, Math.max(280, page.width * 0.36))+ height: parent.height++ Item {+ id: listHeader+ width: parent.width+ height: 56+ Segmented {+ anchors.left: parent.left+ anchors.leftMargin: 16+ anchors.verticalCenter: parent.verticalCenter+ options: [+ { value: "recent", label: qsTr("Recent") },+ { value: "contacts", label: qsTr("Contacts") }+ ]+ value: page.tab+ onPicked: (v) => page.tab = v+ }+ IconButton {+ anchors.right: parent.right+ anchors.rightMargin: 10+ anchors.verticalCenter: parent.verticalCenter+ iconPath: Icons.refresh+ label: qsTr("Refresh")+ enabled: PhoneCall.logStatus !== "loading" && PhoneCall.contactsStatus !== "loading"+ onClicked: PhoneCall.refresh()+ }+ }++ // Search: by name or number.+ Rectangle {+ id: searchBox+ anchors.top: listHeader.bottom+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.leftMargin: 16+ anchors.rightMargin: 16+ height: 38+ radius: Theme.graphite ? Theme.radiusSm : height / 2+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHighest+ border.width: search.activeFocus ? 2 : (Theme.graphite ? 1 : 0)+ border.color: search.activeFocus ? Theme.primary : Theme.outlineVariant+ Icon {+ id: searchIcon+ anchors.left: parent.left+ anchors.leftMargin: 12+ anchors.verticalCenter: parent.verticalCenter+ width: 16; height: 16+ path: Icons.search+ color: Theme.surfaceContentVariant+ }+ TextInput {+ id: search+ anchors.left: searchIcon.right+ anchors.leftMargin: 8+ anchors.right: clearSearch.left+ anchors.verticalCenter: parent.verticalCenter+ font.family: Theme.fontUi+ font.pixelSize: 14+ color: Theme.surfaceContent+ selectionColor: Theme.primaryContainer+ selectedTextColor: Theme.primaryContainerContent+ clip: true+ Accessible.name: page.tab === "recent" ? qsTr("Search calls") : qsTr("Search contacts")+ Keys.onEscapePressed: (event) => {+ event.accepted = text.length > 0+ text = ""+ }+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ visible: search.text.length === 0+ role: "body"+ muted: true+ text: page.tab === "recent" ? qsTr("Search calls") : qsTr("Search contacts")+ }+ }+ IconButton {+ id: clearSearch+ anchors.right: parent.right+ anchors.rightMargin: 2+ anchors.verticalCenter: parent.verticalCenter+ width: 32; height: 32+ visible: search.text.length > 0+ iconPath: Icons.close+ label: qsTr("Clear search")+ onClicked: search.text = ""+ }+ }++ // ---- Recent calls tab ----+ Item {+ anchors.top: searchBox.bottom+ anchors.topMargin: 8+ anchors.bottom: parent.bottom+ width: parent.width+ visible: page.tab === "recent"++ Spinner {+ anchors.centerIn: parent+ visible: PhoneCall.logStatus === "loading" && page.callLog.length === 0+ }++ // Permission / toggle / error state for call log.+ Column {+ anchors.centerIn: parent+ width: parent.width - 40+ spacing: 10+ visible: page.callLog.length === 0 && PhoneCall.logStatus !== "loading" && PhoneCall.logStatus !== "ready"+ Icon {+ anchors.horizontalCenter: parent.horizontalCenter+ width: 32; height: 32+ stroke: 1.5+ path: Icons.call+ color: Theme.surfaceContentVariant+ }+ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.WordWrap+ role: "title"+ size: 15+ text: PhoneCall.logStatus === "off" ? qsTr("Calls are off for %1").arg(page.deviceName)+ : PhoneCall.logStatus === "unsupported" ? qsTr("Allow call log on %1").arg(page.deviceName)+ : PhoneCall.logStatus === "offline" ? qsTr("%1 isn't connected").arg(page.deviceName)+ : qsTr("Couldn't load recent calls")+ }+ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.WordWrap+ role: "bodySmall"+ muted: true+ text: PhoneCall.logStatus === "off" ? qsTr("Turn on Calls for this phone, here in Settings and in the Nectarlink app on the phone.")+ : PhoneCall.logStatus === "unsupported" ? qsTr("In the Nectarlink app on your phone, tap Allow on “Call log” or “Call and answer”.")+ : PhoneCall.logStatus === "offline" ? qsTr("Your recent calls show up here when it's back.")+ : qsTr("Something went wrong reading the call log from the phone.")+ }+ Button {+ anchors.horizontalCenter: parent.horizontalCenter+ visible: PhoneCall.logStatus === "failed"+ variant: "tonal"+ size: "sm"+ text: qsTr("Try again")+ onClicked: PhoneCall.refresh()+ }+ }++ ListView {+ id: recentList+ anchors.fill: parent+ visible: page.callLog.length > 0 || PhoneCall.logStatus === "ready"+ clip: true+ boundsBehavior: Flickable.StopAtBounds+ model: page.shownCalls+ onAtYEndChanged: if (atYEnd && PhoneCall.moreLog && count > 0) PhoneCall.loadOlder()+ delegate: CallRow {+ width: recentList.width+ entry: modelData+ previous: index > 0 ? page.shownCalls[index - 1] : null+ }+ footer: Item {+ width: recentList.width+ height: PhoneCall.loadingOlder ? 44 : 0+ Spinner { anchors.centerIn: parent; visible: PhoneCall.loadingOlder }+ }+ Txt {+ anchors.centerIn: parent+ visible: PhoneCall.logStatus === "ready" && page.shownCalls.length === 0+ role: "body"+ muted: true+ text: page.query.length > 0 ? qsTr("No calls match.") : qsTr("No recent calls.")+ }+ }+ }++ // ---- Contacts tab ----+ Item {+ anchors.top: searchBox.bottom+ anchors.topMargin: 8+ anchors.bottom: parent.bottom+ width: parent.width+ visible: page.tab === "contacts"++ Spinner {+ anchors.centerIn: parent+ visible: PhoneCall.contactsStatus === "loading" && page.contacts.length === 0+ }++ // Permission / toggle / error state for contacts.+ Column {+ anchors.centerIn: parent+ width: parent.width - 40+ spacing: 10+ visible: page.contacts.length === 0 && PhoneCall.contactsStatus !== "loading" && PhoneCall.contactsStatus !== "ready"+ Icon {+ anchors.horizontalCenter: parent.horizontalCenter+ width: 32; height: 32+ stroke: 1.5+ path: Icons.person+ color: Theme.surfaceContentVariant+ }+ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.WordWrap+ role: "title"+ size: 15+ text: PhoneCall.contactsStatus === "off" ? qsTr("Contacts are off for %1").arg(page.deviceName)+ : PhoneCall.contactsStatus === "unsupported" ? qsTr("Allow contacts on %1").arg(page.deviceName)+ : PhoneCall.contactsStatus === "offline" ? qsTr("%1 isn't connected").arg(page.deviceName)+ : qsTr("Couldn't load contacts")+ }+ Txt {+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ wrapMode: Text.WordWrap+ role: "bodySmall"+ muted: true+ text: PhoneCall.contactsStatus === "off" ? qsTr("Turn on Contacts for this phone, here in Settings and in the Nectarlink app on the phone.")+ : PhoneCall.contactsStatus === "unsupported" ? qsTr("In the Nectarlink app on your phone, tap Allow on “Contacts”.")+ : PhoneCall.contactsStatus === "offline" ? qsTr("Your contacts show up here when it's back.")+ : qsTr("Something went wrong reading contacts from the phone.")+ }+ Button {+ anchors.horizontalCenter: parent.horizontalCenter+ visible: PhoneCall.contactsStatus === "failed"+ variant: "tonal"+ size: "sm"+ text: qsTr("Try again")+ onClicked: PhoneCall.refresh()+ }+ }++ ListView {+ id: contactList+ anchors.fill: parent+ visible: page.contacts.length > 0 || PhoneCall.contactsStatus === "ready"+ clip: true+ boundsBehavior: Flickable.StopAtBounds+ model: page.shownContacts+ delegate: ContactRow {+ width: contactList.width+ contact: modelData+ previous: index > 0 ? page.shownContacts[index - 1] : null+ }+ Txt {+ anchors.centerIn: parent+ visible: PhoneCall.contactsStatus === "ready" && page.shownContacts.length === 0+ role: "body"+ muted: true+ text: page.query.length > 0 ? qsTr("No contacts match.") : qsTr("No contacts on this phone.")+ }+ }+ }++ Divider { anchors.right: parent.right; width: 1; height: parent.height }+ }++ // ---- Right pane: Active call, selected contact, and keypad dialer ----+ Flickable {+ id: rightPane+ visible: !page.phoneOffline+ anchors.left: list.right+ anchors.right: parent.right+ height: parent.height+ contentHeight: Math.max(height, rightColumn.height + Theme.contentPadding * 2)+ boundsBehavior: Flickable.StopAtBounds+ clip: true++ Column {+ id: rightColumn+ width: Math.min(380, rightPane.width - Theme.contentPadding * 2)+ x: Math.max(Theme.contentPadding, (rightPane.width - width) / 2)+ y: Math.max(Theme.contentPadding, (rightPane.height - height) / 2)+ spacing: 16++ // Active call on the phone (reuses CallCard).+ CallCard {+ width: parent.width+ visible: PhoneCall.active && PhoneCall.device === page.deviceId+ }++ // Selected contact details (when a contact with one or more numbers is clicked).+ Card {+ id: contactDetailCard+ width: parent.width+ visible: page.selectedContact !== null+ Column {+ width: parent.width+ spacing: 10+ Item {+ width: parent.width+ height: 44+ Item {+ id: detailAvatar+ width: 40; height: 40+ anchors.verticalCenter: parent.verticalCenter+ RoundedImage {+ anchors.fill: parent+ radius: width / 2+ visible: (page.selectedContact ? page.selectedContact.photo : "").length > 0 && status === Image.Ready+ source: page.selectedContact ? page.selectedContact.photo : ""+ sourceSize: Qt.size(80, 80)+ fillMode: Image.PreserveAspectCrop+ }+ Avatar {+ anchors.fill: parent+ visible: !page.selectedContact || page.selectedContact.photo.length === 0+ name: page.selectedContact ? page.selectedContact.name : ""+ hue: page.selectedContact ? page.hueOf(page.selectedContact.name) : -1+ }+ }+ Column {+ anchors.left: detailAvatar.right+ anchors.leftMargin: 12+ anchors.right: closeDetail.left+ anchors.rightMargin: 8+ anchors.verticalCenter: parent.verticalCenter+ spacing: 2+ Row {+ spacing: 6+ Txt {+ text: page.selectedContact ? page.selectedContact.name : ""+ role: "title"+ elide: Text.ElideRight+ }+ Icon {+ anchors.verticalCenter: parent.verticalCenter+ visible: !!(page.selectedContact && page.selectedContact.starred)+ width: 14; height: 14+ path: Icons.star+ color: Theme.primary+ }+ }+ }+ IconButton {+ id: closeDetail+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ width: 32; height: 32+ iconPath: Icons.close+ label: qsTr("Close contact")+ onClicked: page.selectedContact = null+ }+ }++ Repeater {+ model: page.selectedContact ? (page.selectedContact.numbers || []) : []+ delegate: Item {+ id: numRow+ required property var modelData+ width: parent.width+ height: 44+ Column {+ anchors.left: parent.left+ anchors.right: numActions.left+ anchors.rightMargin: 8+ anchors.verticalCenter: parent.verticalCenter+ Txt {+ width: parent.width+ text: numRow.modelData.number+ role: "body"+ elide: Text.ElideRight+ }+ Txt {+ width: parent.width+ visible: (numRow.modelData.label || "").length > 0+ text: numRow.modelData.label || ""+ role: "caption"+ muted: true+ elide: Text.ElideRight+ }+ }+ Row {+ id: numActions+ anchors.right: parent.right+ anchors.verticalCenter: parent.verticalCenter+ spacing: 4+ IconButton {+ width: 34; height: 34+ iconPath: Icons.copy+ label: qsTr("Copy number")+ onClicked: PhoneCall.copy(numRow.modelData.number)+ }+ IconButton {+ width: 34; height: 34+ iconPath: Icons.messages+ label: qsTr("Text %1").arg(numRow.modelData.number)+ onClicked: page.startText(numRow.modelData.number, page.selectedContact ? page.selectedContact.name : "")+ }+ IconButton {+ width: 34; height: 34+ tonal: true+ enabled: PhoneCall.canDial && !PhoneCall.dialing+ iconPath: Icons.call+ label: qsTr("Call %1").arg(numRow.modelData.number)+ onClicked: {+ dialInput.text = numRow.modelData.number+ page.placeCall(numRow.modelData.number)+ }+ }+ }+ }+ }+ }+ }++ // ---- Dialer / Keypad ----+ Card {+ id: dialerCard+ width: parent.width++ readonly property var dialFeature: AppController.capsRevision >= 0 && page.deviceId.length > 0+ ? AppController.featureState(page.deviceId, "calls.dial") : ({})++ Column {+ width: parent.width+ spacing: 14++ // Number entry box + backspace.+ Rectangle {+ width: parent.width+ height: dialMatch.visible ? 64 : 52+ radius: Theme.graphite ? Theme.radiusSm : Theme.radiusLg+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHighest+ border.width: dialInput.activeFocus ? 2 : (Theme.graphite ? 1 : 0)+ border.color: dialInput.activeFocus ? Theme.primary : Theme.outlineVariant++ Column {+ anchors.left: parent.left+ anchors.leftMargin: 16+ anchors.right: backspaceButton.visible ? backspaceButton.left : parent.right+ anchors.rightMargin: 8+ anchors.verticalCenter: parent.verticalCenter+ spacing: 2++ TextInput {+ id: dialInput+ width: parent.width+ horizontalAlignment: TextInput.AlignHCenter+ font.family: Theme.fontMono+ font.pixelSize: 20+ font.weight: 600+ color: Theme.surfaceContent+ selectionColor: Theme.primaryContainer+ selectedTextColor: Theme.primaryContainerContent+ inputMethodHints: Qt.ImhDialableCharactersOnly+ clip: true+ Accessible.name: qsTr("Phone number to call")+ Keys.onReturnPressed: page.placeCall(dialInput.text)+ Keys.onEnterPressed: page.placeCall(dialInput.text)+ Txt {+ anchors.centerIn: parent+ visible: dialInput.text.length === 0+ role: "body"+ muted: true+ text: qsTr("Enter a number")+ }+ }+ Txt {+ id: dialMatch+ width: parent.width+ horizontalAlignment: Text.AlignHCenter+ visible: page.dialMatchedContact !== null+ role: "caption"+ color: Theme.primary+ elide: Text.ElideRight+ text: page.dialMatchedContact+ ? (page.dialMatchedContact.label.length > 0+ ? page.dialMatchedContact.name + " · " + page.dialMatchedContact.label+ : page.dialMatchedContact.name)+ : ""+ }+ }++ IconButton {+ id: backspaceButton+ anchors.right: parent.right+ anchors.rightMargin: 6+ anchors.verticalCenter: parent.verticalCenter+ width: 36; height: 36+ visible: dialInput.text.length > 0+ iconPath: Icons.backspace+ label: qsTr("Backspace")+ onClicked: dialInput.text = dialInput.text.slice(0, -1)+ }+ }++ // 3x4 telephone keypad.+ Grid {+ anchors.horizontalCenter: parent.horizontalCenter+ columns: 3+ columnSpacing: 12+ rowSpacing: 10+ Repeater {+ model: [+ { digit: "1", sub: "" },+ { digit: "2", sub: "ABC" },+ { digit: "3", sub: "DEF" },+ { digit: "4", sub: "GHI" },+ { digit: "5", sub: "JKL" },+ { digit: "6", sub: "MNO" },+ { digit: "7", sub: "PQRS" },+ { digit: "8", sub: "TUV" },+ { digit: "9", sub: "WXYZ" },+ { digit: "*", sub: "" },+ { digit: "0", sub: "+" },+ { digit: "#", sub: "" }+ ]+ delegate: Rectangle {+ id: padKey+ required property var modelData+ width: 84; height: 50+ radius: Theme.pill(height)+ color: padTap.pressed+ ? Theme.secondaryContainer+ : padHover.hovered+ ? Qt.rgba(Theme.surfaceContent.r, Theme.surfaceContent.g, Theme.surfaceContent.b, 0.08)+ : (Theme.graphite ? "transparent" : Theme.surfaceContainerHigh)+ border.width: Theme.graphite ? 1 : 0+ border.color: Theme.outlineVariant+ scale: padTap.pressed ? Theme.pressScale : 1+ Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }++ function tapDigit(ch) {+ dialInput.text = dialInput.text + ch+ if (PhoneCall.active && PhoneCall.controls)+ PhoneCall.press(ch)+ }++ Accessible.role: Accessible.Button+ Accessible.name: modelData.sub.length > 0 ? modelData.digit + " " + modelData.sub : modelData.digit+ Accessible.onPressAction: tapDigit(modelData.digit)++ Column {+ anchors.centerIn: parent+ spacing: -2+ Txt {+ anchors.horizontalCenter: parent.horizontalCenter+ role: "title"+ size: 18+ text: padKey.modelData.digit+ }+ Txt {+ anchors.horizontalCenter: parent.horizontalCenter+ visible: padKey.modelData.sub.length > 0+ role: "caption"+ size: 9+ muted: true+ text: padKey.modelData.sub+ }+ }+ HoverHandler { id: padHover; cursorShape: Qt.PointingHandCursor }+ TapHandler {+ id: padTap+ onTapped: padKey.tapDigit(padKey.modelData.digit)+ onLongPressed: {+ if (padKey.modelData.digit === "0")+ padKey.tapDigit("+")+ }+ }+ }+ }+ }++ // Call and Text buttons.+ Row {+ anchors.horizontalCenter: parent.horizontalCenter+ spacing: 14++ Button {+ anchors.verticalCenter: parent.verticalCenter+ variant: "tonal"+ iconPath: Icons.messages+ text: qsTr("Text")+ enabled: dialInput.text.trim().length > 0+ onClicked: page.startText(+ dialInput.text,+ page.dialMatchedContact ? page.dialMatchedContact.name : ""+ )+ }++ Button {+ anchors.verticalCenter: parent.verticalCenter+ variant: "fill"+ iconPath: Icons.call+ text: PhoneCall.dialing ? qsTr("Calling…") : qsTr("Call")+ enabled: dialInput.text.trim().length > 0 && PhoneCall.canDial && !PhoneCall.dialing+ onClicked: page.placeCall(dialInput.text)+ }++ IconButton {+ anchors.verticalCenter: parent.verticalCenter+ visible: dialInput.text.length > 0+ iconPath: Icons.close+ label: qsTr("Clear number")+ onClicked: dialInput.text = ""+ }+ }++ LockChip {+ anchors.horizontalCenter: parent.horizontalCenter+ visible: !PhoneCall.canDial && label.length > 0+ feature: dialerCard.dialFeature+ }+ }+ }+ }+ }++ // ---- A row in the Recent calls list ----+ component CallRow: Item {+ id: row+ property var entry+ property var previous: null+ readonly property bool newDay: !previous || new Date(previous.date).toDateString() !== new Date(entry.date).toDateString()+ readonly property bool missed: entry.direction === "missed"+ readonly property string displayName: (entry.name && entry.name.length > 0) ? entry.name : entry.number+ readonly property bool named: !!(entry.name && entry.name.length > 0 && !/^[\d+(#*]/.test(entry.name))+ readonly property string durText: page.formatDuration(entry.duration)+ readonly property string dirLabel: entry.direction === "missed" ? qsTr("Missed")+ : entry.direction === "outgoing" ? qsTr("Outgoing")+ : entry.direction === "rejected" ? qsTr("Declined")+ : qsTr("Incoming")++ height: dayHeader.height + 68+ Accessible.role: Accessible.ListItem+ Accessible.name: displayName + ", " + dirLabel + ", " + page.shortTime(entry.date)+ Accessible.onPressAction: selectCall()++ function selectCall() {+ dialInput.text = entry.number+ }++ // Day separator ("Today", "Yesterday", date).+ Txt {+ id: dayHeader+ width: parent.width+ height: row.newDay ? implicitHeight + 18 : 0+ visible: row.newDay+ topPadding: 10+ leftPadding: 20+ role: "label"+ muted: true+ text: page.dayLabel(row.entry.date)+ }++ Item {+ anchors.top: dayHeader.bottom+ width: parent.width+ height: 68++ Rectangle {+ anchors.fill: parent+ anchors.leftMargin: 8+ anchors.rightMargin: 8+ radius: Theme.radiusLg+ color: callHover.hovered+ ? Qt.rgba(Theme.surfaceContent.r, Theme.surfaceContent.g, Theme.surfaceContent.b, 0.06)+ : "transparent"+ Behavior on color { ColorAnimation { duration: Theme.fadeFast } }+ }++ Item {+ id: callFace+ x: 20+ anchors.verticalCenter: parent.verticalCenter+ width: 40; height: 40+ RoundedImage {+ anchors.fill: parent+ radius: width / 2+ visible: (row.entry.photo || "").length > 0 && status === Image.Ready+ source: row.entry.photo || ""+ sourceSize: Qt.size(80, 80)+ fillMode: Image.PreserveAspectCrop+ }+ Avatar {+ anchors.fill: parent+ visible: (row.entry.photo || "").length === 0+ name: row.named ? row.displayName : ""+ iconPath: row.named ? "" : Icons.person+ hue: row.named ? page.hueOf(row.displayName) : -1+ emphasized: row.missed+ }+ }++ Column {+ anchors.left: callFace.right+ anchors.leftMargin: 12+ anchors.right: callRowActions.left+ anchors.rightMargin: 8+ anchors.verticalCenter: parent.verticalCenter+ spacing: 2++ Txt {+ width: parent.width+ text: row.displayName+ role: "body"+ weight: row.missed ? 650 : 500+ color: row.missed ? Theme.error : Theme.surfaceContent+ elide: Text.ElideRight+ }++ Row {+ width: parent.width+ spacing: 5+ Icon {+ anchors.verticalCenter: parent.verticalCenter+ width: 13; height: 13+ stroke: 2+ path: row.missed ? Icons.callMissed+ : row.entry.direction === "outgoing" ? Icons.callOutgoing+ : Icons.callIncoming+ color: row.missed ? Theme.error : Theme.surfaceContentVariant+ }+ Txt {+ width: parent.width - 18+ role: "bodySmall"+ color: row.missed ? Theme.error : Theme.surfaceContentVariant+ elide: Text.ElideRight+ text: {+ const parts = [row.dirLabel]+ if (row.durText.length > 0)+ parts.push(row.durText)+ parts.push(page.shortTime(row.entry.date))+ return parts.join(" · ")+ }+ }+ }+ }++ Row {+ id: callRowActions+ anchors.right: parent.right+ anchors.rightMargin: 14+ anchors.verticalCenter: parent.verticalCenter+ spacing: 2+ IconButton {+ width: 34; height: 34+ iconPath: Icons.messages+ label: qsTr("Text %1").arg(row.displayName)+ onClicked: page.startText(row.entry.number, row.entry.name || "")+ }+ IconButton {+ width: 34; height: 34+ tonal: callHover.hovered+ enabled: PhoneCall.canDial && !PhoneCall.dialing && row.entry.number.length > 0+ iconPath: Icons.call+ label: qsTr("Call %1").arg(row.displayName)+ onClicked: {+ dialInput.text = row.entry.number+ page.placeCall(row.entry.number)+ }+ }+ }++ HoverHandler { id: callHover; cursorShape: Qt.PointingHandCursor }+ TapHandler { onTapped: row.selectCall() }+ }+ }++ // ---- A row in the Contacts list ----+ component ContactRow: Item {+ id: crow+ property var contact+ property var previous: null+ readonly property var primaryEntry: (contact.numbers && contact.numbers.length > 0) ? contact.numbers[0] : null+ readonly property string primaryNumber: primaryEntry ? primaryEntry.number : ""+ readonly property string primaryLabel: primaryEntry && primaryEntry.label ? primaryEntry.label : ""+ readonly property bool selected: page.selectedContact !== null && page.selectedContact.id === contact.id+ // Section header ("Favorites" / "All contacts") when not filtering.+ readonly property bool showSection: page.query.length === 0+ && (!previous || previous.starred !== contact.starred)++ height: sectionLabel.height + 68+ Accessible.role: Accessible.ListItem+ Accessible.name: contact.name + (primaryNumber.length > 0 ? ", " + primaryNumber : "")+ Accessible.onPressAction: pickContact()++ function pickContact() {+ page.selectedContact = contact+ if (primaryNumber.length > 0)+ dialInput.text = primaryNumber+ }++ Row {+ id: sectionLabel+ x: 20+ height: crow.showSection ? 28 : 0+ visible: crow.showSection+ spacing: 6+ Icon {+ anchors.verticalCenter: parent.verticalCenter+ visible: !!crow.contact.starred+ width: 13; height: 13+ path: Icons.star+ color: Theme.primary+ }+ Txt {+ anchors.verticalCenter: parent.verticalCenter+ role: "label"+ muted: true+ text: crow.contact.starred ? qsTr("Favorites") : qsTr("Contacts")+ }+ }++ Item {+ anchors.top: sectionLabel.bottom+ width: parent.width+ height: 68++ Rectangle {+ anchors.fill: parent+ anchors.leftMargin: 8+ anchors.rightMargin: 8+ radius: Theme.radiusLg+ color: crow.selected ? Theme.secondaryContainer+ : contactHover.hovered ? Qt.rgba(Theme.surfaceContent.r, Theme.surfaceContent.g, Theme.surfaceContent.b, 0.06)+ : "transparent"+ Behavior on color { ColorAnimation { duration: Theme.fadeFast } }+ }++ Item {+ id: contactFace+ x: 20+ anchors.verticalCenter: parent.verticalCenter+ width: 40; height: 40+ RoundedImage {+ anchors.fill: parent+ radius: width / 2+ visible: (crow.contact.photo || "").length > 0 && status === Image.Ready+ source: crow.contact.photo || ""+ sourceSize: Qt.size(80, 80)+ fillMode: Image.PreserveAspectCrop+ }+ Avatar {+ anchors.fill: parent+ visible: (crow.contact.photo || "").length === 0+ name: crow.contact.name+ hue: page.hueOf(crow.contact.name)+ emphasized: !!crow.contact.starred+ }+ }++ Column {+ anchors.left: contactFace.right+ anchors.leftMargin: 12+ anchors.right: contactActions.left+ anchors.rightMargin: 8+ anchors.verticalCenter: parent.verticalCenter+ spacing: 2++ Row {+ width: parent.width+ spacing: 6+ Txt {+ width: Math.min(implicitWidth, parent.width - (crow.contact.starred ? 20 : 0))+ text: crow.contact.name+ role: "body"+ weight: 500+ elide: Text.ElideRight+ }+ Icon {+ anchors.verticalCenter: parent.verticalCenter+ visible: !!crow.contact.starred+ width: 13; height: 13+ path: Icons.star+ color: Theme.primary+ }+ }++ Txt {+ width: parent.width+ role: "bodySmall"+ muted: true+ elide: Text.ElideRight+ text: {+ const parts = []+ if (crow.primaryLabel.length > 0)+ parts.push(crow.primaryLabel)+ if (crow.primaryNumber.length > 0)+ parts.push(crow.primaryNumber)+ const extra = (crow.contact.numbers ? crow.contact.numbers.length : 0) - 1+ if (extra > 0)+ parts.push(qsTr("+%1 more").arg(extra))+ return parts.join(" · ")+ }+ }+ }++ Row {+ id: contactActions+ anchors.right: parent.right+ anchors.rightMargin: 14+ anchors.verticalCenter: parent.verticalCenter+ spacing: 2+ IconButton {+ width: 34; height: 34+ visible: crow.primaryNumber.length > 0+ iconPath: Icons.messages+ label: qsTr("Text %1").arg(crow.contact.name)+ onClicked: page.startText(crow.primaryNumber, crow.contact.name)+ }+ IconButton {+ width: 34; height: 34+ visible: crow.primaryNumber.length > 0+ tonal: contactHover.hovered+ enabled: PhoneCall.canDial && !PhoneCall.dialing+ iconPath: Icons.call+ label: qsTr("Call %1").arg(crow.contact.name)+ onClicked: {+ dialInput.text = crow.primaryNumber+ page.placeCall(crow.primaryNumber)+ }+ }+ }++ HoverHandler { id: contactHover; cursorShape: Qt.PointingHandCursor }+ TapHandler { onTapped: crow.pickContact() }+ }+ }+}diff --git a/desktop/app/qml/pages/MessagesPage.qml b/desktop/app/qml/pages/MessagesPage.qmlindex 6248c1c..3336f29 100644--- a/desktop/app/qml/pages/MessagesPage.qml+++ b/desktop/app/qml/pages/MessagesPage.qml@@ -15,6 +15,7 @@ Item {readonly property var threads: { try { return JSON.parse(Messages.threads) } catch (e) { return [] } }readonly property var messages: { try { return JSON.parse(Messages.messages) } catch (e) { return [] } }+ readonly property var contacts: { try { return JSON.parse(PhoneCall.contacts) } catch (e) { return [] } }readonly property var openThread: threads.find(t => t.id === Messages.thread) || nullreadonly property bool ready: Messages.status === "ready"// Conversations matching the search box.@@ -22,6 +23,32 @@ Item {readonly property var shownThreads: query.length === 0 ? threads: threads.filter(t => (t.title + " " + t.addresses + " " + t.snippet).toLocaleLowerCase().indexOf(query) >= 0)+ // Contacts matching the "To" field when starting a new message.+ readonly property string recipientQuery: toField.text.trim().toLocaleLowerCase()+ readonly property var recipientMatches: {+ if (!composing || recipientQuery.length === 0) return []+ const out = []+ for (let i = 0; i < contacts.length && out.length < 6; i++) {+ const c = contacts[i]+ const nums = c.numbers || []+ for (let j = 0; j < nums.length && out.length < 6; j++) {+ const num = nums[j].number || ""+ const label = nums[j].label || ""+ // Don't show a suggestion if its number is already selected verbatim.+ if (num === toField.text.trim()) continue+ if ((c.name + " " + num + " " + label).toLocaleLowerCase().indexOf(recipientQuery) >= 0) {+ out.push({+ name: c.name,+ number: num,+ label: label,+ photo: c.photo || ""+ })+ }+ }+ }+ return out+ }+// Back to the list: nothing open.function closeChat() {Messages.closeThread()@@ -70,9 +97,28 @@ Item {Behavior on y { SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }}+ function applyComposeTarget() {+ if (Messages.composeTo.length > 0) {+ composing = true+ toField.text = Messages.composeTo+ Qt.callLater(() => composer.focusText())+ } else if (Messages.thread.length > 0) {+ composing = false+ }+ }++ Connections {+ target: Messages+ function onComposeToChanged() { page.applyComposeTarget() }+ function onThreadChanged() { if (Messages.thread.length > 0) page.composing = false }+ }+function load() {- if (active && deviceId.length > 0)+ if (active && deviceId.length > 0) {Messages.open(deviceId)+ PhoneCall.ensureContacts(deviceId)+ applyComposeTarget()+ }}// Leaving the page closes the open conversation.onActiveChanged: active ? load() : closeChat()@@ -95,6 +141,7 @@ Item {function startNew() {Messages.closeThread()composing = true+ toField.text = ""toField.forceActiveFocus()}onDeviceIdChanged: { composing = false; load() }@@ -318,8 +365,8 @@ Item {Column {anchors.left: backButton.rightanchors.leftMargin: 8- anchors.right: parent.right- anchors.rightMargin: 24+ anchors.right: callThreadButton.visible ? callThreadButton.left : parent.right+ anchors.rightMargin: callThreadButton.visible ? 8 : 24anchors.verticalCenter: parent.verticalCenterspacing: 2visible: !page.composing@@ -338,6 +385,18 @@ Item {elide: Text.ElideRight}}+ IconButton {+ id: callThreadButton+ anchors.right: parent.right+ anchors.rightMargin: 14+ anchors.verticalCenter: parent.verticalCenter+ visible: !page.composing && !!page.openThread && !page.openThread.group+ && page.openThread.addresses.length > 0 && PhoneCall.canDial+ enabled: !PhoneCall.dialing+ iconPath: Icons.call+ label: page.openThread ? qsTr("Call %1").arg(page.openThread.title) : qsTr("Call")+ onClicked: if (page.openThread) PhoneCall.dial(page.openThread.addresses)+ }// New message: who to.Row {anchors.left: backButton.right@@ -357,22 +416,120 @@ Item {color: Theme.surfaceContentselectionColor: Theme.primaryContainerselectedTextColor: Theme.primaryContainerContent- inputMethodHints: Qt.ImhDialableCharactersOnlyclip: true- Accessible.name: qsTr("Phone number")- Keys.onReturnPressed: composer.focusText()+ Accessible.name: qsTr("Name or phone number")+ Keys.onReturnPressed: {+ if (page.recipientMatches.length > 0 && !/\d/.test(toField.text)) {+ toField.text = page.recipientMatches[0].number+ }+ composer.focusText()+ }Txt {anchors.verticalCenter: parent.verticalCentervisible: toField.text.length === 0role: "body"muted: true- text: qsTr("Phone number")+ text: qsTr("Name or phone number")}}}Divider { anchors.bottom: parent.bottom; width: parent.width }}+ // Contact suggestions when typing a name or number in "To".+ Rectangle {+ id: contactSuggestions+ z: 2+ anchors.top: chatHeader.bottom+ anchors.left: parent.left+ anchors.right: parent.right+ anchors.leftMargin: 24+ anchors.rightMargin: 24+ anchors.topMargin: 6+ visible: page.composing && page.recipientMatches.length > 0+ height: suggestionColumn.height + 12+ radius: Theme.radiusLg+ color: Theme.surfaceContainerHigh+ border.width: 1+ border.color: Theme.outlineVariant++ Column {+ id: suggestionColumn+ y: 6+ width: parent.width+ Repeater {+ model: page.recipientMatches+ delegate: Item {+ id: srow+ required property var modelData+ width: suggestionColumn.width+ height: 52+ Accessible.role: Accessible.ListItem+ Accessible.name: modelData.name + ", " + modelData.number+ Accessible.onPressAction: choose()+ function choose() {+ toField.text = modelData.number+ composer.focusText()+ }+ Rectangle {+ anchors.fill: parent+ anchors.leftMargin: 6+ anchors.rightMargin: 6+ radius: Theme.radiusMd+ color: sHover.hovered+ ? Qt.rgba(Theme.surfaceContent.r, Theme.surfaceContent.g, Theme.surfaceContent.b, 0.08)+ : "transparent"+ }+ Item {+ id: sFace+ x: 16+ anchors.verticalCenter: parent.verticalCenter+ width: 34; height: 34+ RoundedImage {+ anchors.fill: parent+ radius: width / 2+ visible: srow.modelData.photo.length > 0 && status === Image.Ready+ source: srow.modelData.photo+ sourceSize: Qt.size(68, 68)+ fillMode: Image.PreserveAspectCrop+ }+ Avatar {+ anchors.fill: parent+ visible: srow.modelData.photo.length === 0+ name: srow.modelData.name+ hue: page.hueOf(srow.modelData.name)+ }+ }+ Column {+ anchors.left: sFace.right+ anchors.leftMargin: 12+ anchors.right: parent.right+ anchors.rightMargin: 16+ anchors.verticalCenter: parent.verticalCenter+ Txt {+ width: parent.width+ text: srow.modelData.name+ role: "body"+ weight: 500+ elide: Text.ElideRight+ }+ Txt {+ width: parent.width+ text: srow.modelData.label.length > 0+ ? srow.modelData.label + " · " + srow.modelData.number+ : srow.modelData.number+ role: "bodySmall"+ muted: true+ elide: Text.ElideRight+ }+ }+ HoverHandler { id: sHover; cursorShape: Qt.PointingHandCursor }+ TapHandler { onTapped: srow.choose() }+ }+ }+ }+ }+ListView {id: messageListanchors.top: chatHeader.bottomdiff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qmlindex bf92b9a..52c6f08 100644--- a/desktop/app/qml/pages/SettingsPage.qml+++ b/desktop/app/qml/pages/SettingsPage.qml@@ -21,6 +21,7 @@ Item {notifications: qsTr("Notifications"),messages: qsTr("Messages"),calls: qsTr("Calls"),+ contacts: qsTr("Contacts"),clipboard: qsTr("Clipboard"),files: qsTr("Files"),media: qsTr("Media playing on either device"),diff --git a/desktop/app/src/bridge/calls.rs b/desktop/app/src/bridge/calls.rsindex 8b791df..6c0aa9a 100644--- a/desktop/app/src/bridge/calls.rs+++ b/desktop/app/src/bridge/calls.rs@@ -1,6 +1,7 @@// 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.+//! `PhoneCall`: the call in progress on the phone Home and Calls show, the+//! controls QML sends to it, the phone's call log and contacts, and dialing+//! a number from the PC.use std::pin::Pin;@@ -39,6 +40,21 @@ pub mod qobject {#[qproperty(bool, speaker)]#[qproperty(bool, held)]#[qproperty(bool, can_hold, cxx_name = "canHold")]+ /// Call log status: "idle", "loading", "ready", "offline", "off", "unsupported" or "failed".+ #[qproperty(QString, log_status, cxx_name = "logStatus")]+ /// Recent calls, newest first (JSON).+ #[qproperty(QString, call_log, cxx_name = "callLog")]+ /// Older call log entries can be loaded.+ #[qproperty(bool, more_log, cxx_name = "moreLog")]+ #[qproperty(bool, loading_older, cxx_name = "loadingOlder")]+ /// Contacts status: "idle", "loading", "ready", "offline", "off", "unsupported" or "failed".+ #[qproperty(QString, contacts_status, cxx_name = "contactsStatus")]+ /// Contacts, favorites first (JSON).+ #[qproperty(QString, contacts)]+ /// The PC can ask the phone to dial a number.+ #[qproperty(bool, can_dial, cxx_name = "canDial")]+ /// A dial request is on its way to the phone.+ #[qproperty(bool, dialing)]type PhoneCall = super::PhoneCallRust;}@@ -48,6 +64,25 @@ pub mod qobject {unsafe extern "RustQt" {#[cxx_name = "setDevice"]fn set_device(self: Pin<&mut PhoneCall>, device: QString);+ /// Opens a phone's call log and contacts (reloads when it's the one shown).+ #[qinvokable]+ fn open(self: Pin<&mut PhoneCall>, device: &QString);+ /// Loads a phone's contacts in the background if not yet loaded.+ #[qinvokable]+ #[cxx_name = "ensureContacts"]+ fn ensure_contacts(self: &PhoneCall, device: &QString);+ /// Reads the call log and contacts again.+ #[qinvokable]+ fn refresh(self: &PhoneCall);+ #[qinvokable]+ #[cxx_name = "loadOlder"]+ fn load_older(self: &PhoneCall);+ /// Asks the phone to dial `number`.+ #[qinvokable]+ fn dial(self: &PhoneCall, number: &QString);+ /// Puts text on this PC's clipboard (it isn't sent back to the phone).+ #[qinvokable]+ fn copy(self: &PhoneCall, text: &QString);/// Hangs up.#[qinvokable]fn end(self: &PhoneCall);@@ -82,13 +117,27 @@ pub struct PhoneCallRust {speaker: bool,held: bool,can_hold: bool,+ log_status: QString,+ call_log: QString,+ more_log: bool,+ loading_older: bool,+ contacts_status: QString,+ contacts: QString,+ can_dial: bool,+ dialing: bool,/// The call's ID on the phone, for its commands.call: Option<(DeviceId, String)>,+ /// What the Calls page last showed, to skip JSON updates that changed nothing.+ last_view: Option<calls::View>,}impl cxx_qt::Initialize for qobject::PhoneCall {- fn initialize(self: Pin<&mut Self>) {- super::subscribe(self.qt_thread(), Changes::CALLS | Changes::CAPABILITIES, Self::refresh);+ fn initialize(mut self: Pin<&mut Self>) {+ self.as_mut().set_log_status(QString::from("idle"));+ self.as_mut().set_call_log(QString::from("[]"));+ self.as_mut().set_contacts_status(QString::from("idle"));+ self.as_mut().set_contacts(QString::from("[]"));+ super::subscribe(self.qt_thread(), Changes::CALLS | Changes::CAPABILITIES, Self::refresh_state);}}@@ -99,10 +148,47 @@ impl qobject::PhoneCall {}self.as_mut().rust_mut().device = device;self.as_mut().device_changed();- self.refresh();+ self.refresh_state();+ }++ pub fn open(mut self: Pin<&mut Self>, device: &QString) {+ if self.rust().device != *device {+ self.as_mut().rust_mut().device = device.clone();+ self.as_mut().device_changed();+ }+ if let Some(id) = super::parse_device(device) {+ calls::open_device(id);+ }+ self.refresh_state();}- fn refresh(mut self: Pin<&mut Self>) {+ pub fn ensure_contacts(&self, device: &QString) {+ if let Some(id) = super::parse_device(device) {+ calls::ensure_contacts(id);+ }+ }++ pub fn refresh(&self) {+ calls::reload();+ }++ pub fn load_older(&self) {+ calls::load_older();+ }++ pub fn dial(&self, number: &QString) {+ if let Some(device) = super::parse_device(&self.rust().device) {+ calls::dial(device, String::from(number));+ }+ }++ pub fn copy(&self, text: &QString) {+ if let Err(reason) = crate::win::clipboard::write(&String::from(text)) {+ tracing::warn!(reason, "can't copy");+ }+ }++ fn refresh_state(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);@@ -122,6 +208,7 @@ impl qobject::PhoneCall {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_can_dial(device.is_some_and(calls::can_dial));self.as_mut().set_controls(controls.is_some());let controls = controls.unwrap_or_default();self.as_mut().set_muted(controls.muted);@@ -129,6 +216,24 @@ impl qobject::PhoneCall {self.as_mut().set_held(controls.held);self.as_mut().set_can_hold(controls.can_hold);self.as_mut().set_active(call.is_some());++ let view = calls::view();+ if self.rust().last_view.as_ref() != Some(&view) {+ let last = self.rust().last_view.clone();+ let differs = |f: fn(&calls::View) -> String| last.as_ref().is_none_or(|l| f(l) != f(&view));+ self.as_mut().set_log_status(QString::from(view.log_status.as_str()));+ if differs(|v| v.call_log.to_string()) {+ self.as_mut().set_call_log(QString::from(&view.call_log.to_string()));+ }+ self.as_mut().set_more_log(view.more_log);+ self.as_mut().set_loading_older(view.loading_older);+ self.as_mut().set_contacts_status(QString::from(view.contacts_status.as_str()));+ if differs(|v| v.contacts.to_string()) {+ self.as_mut().set_contacts(QString::from(&view.contacts.to_string()));+ }+ self.as_mut().set_dialing(view.dialing);+ self.as_mut().rust_mut().last_view = Some(view);+ }}fn send(&self, command: CallCommand) {diff --git a/desktop/app/src/bridge/messages.rs b/desktop/app/src/bridge/messages.rsindex a88e9dc..837bcb5 100644--- a/desktop/app/src/bridge/messages.rs+++ b/desktop/app/src/bridge/messages.rs@@ -34,6 +34,9 @@ pub mod qobject {#[qproperty(bool, more)]#[qproperty(bool, loading_older, cxx_name = "loadingOlder")]#[qproperty(bool, sending)]+ /// A number pre-filled in the new-message box ("" for none).+ #[qproperty(QString, compose_to, cxx_name = "composeTo")]+ #[qproperty(QString, compose_name, cxx_name = "composeName")]type Messages = super::MessagesRust;}@@ -47,6 +50,10 @@ pub mod qobject {#[qinvokable]#[cxx_name = "openThread"]fn open_thread(self: &Messages, thread: &QString);+ /// Opens an existing conversation with `number`, or starts a new one.+ #[qinvokable]+ #[cxx_name = "startChat"]+ fn start_chat(self: &Messages, device: &QString, number: &QString, name: &QString);#[qinvokable]#[cxx_name = "closeThread"]fn close_thread(self: &Messages);@@ -79,6 +86,8 @@ pub struct MessagesRust {more: bool,loading_older: bool,sending: bool,+ compose_to: QString,+ compose_name: QString,/// What was last shown, to skip refreshes that change nothing.last: Option<messages::View>,}@@ -113,6 +122,8 @@ impl qobject::Messages {self.as_mut().set_more(view.more);self.as_mut().set_loading_older(view.loading_older);self.as_mut().set_sending(view.sending);+ self.as_mut().set_compose_to(QString::from(view.compose_to.as_deref().unwrap_or_default()));+ self.as_mut().set_compose_name(QString::from(view.compose_name.as_deref().unwrap_or_default()));self.as_mut().rust_mut().last = Some(view);}@@ -126,6 +137,12 @@ impl qobject::Messages {messages::open_thread(String::from(thread));}+ pub fn start_chat(&self, device: &QString, number: &QString, name: &QString) {+ if let Some(device) = super::parse_device(device) {+ messages::start_chat(device, String::from(number), String::from(name));+ }+ }+pub fn close_thread(&self) {messages::close_thread();}diff --git a/desktop/app/src/calls.rs b/desktop/app/src/calls.rsindex a59aaf1..4362857 100644--- a/desktop/app/src/calls.rs+++ b/desktop/app/src/calls.rs@@ -7,15 +7,24 @@use std::{collections::HashMap, path::PathBuf, sync::Mutex};-use nectarlink_core::{CallCommand, CallState, DeviceId, Error, FeatureState, LinkState, NodeEvent};+use nectarlink_core::{+ CallCommand, CallLogEntry, CallState, Contact, DeviceId, Error, FeatureState, LinkState, NodeEvent,+};+use serde_json::{Value, json};use crate::{bridge::app::{describe, show_message},core_host,+ messages::{Status, digits},state::Changes,win::toast::{self, CALL_ANSWER, CALL_DECLINE, CALL_END, Toast},};+/// Call log entries read at a time, and contacts per page.+const LOG_PAGE: u32 = 50;+const CONTACTS_PAGE: u32 = 200;+const MAX_CONTACT_PAGES: u32 = 3;+/// The toast "device" for calls; their key is `<device ID> <call ID>`.pub const TOAST_GROUP: &str = "calls";const ACTION_SILENCE: &str = "silence";@@ -60,26 +69,76 @@ pub fn can_control(device: DeviceId) -> bool {})}+/// Whether the PC can ask a phone to dial a number.+pub fn can_dial(device: DeviceId) -> bool {+ core_host::host().hub.read(|s| {+ s.matrices.get(&device).and_then(|m| m.state("calls.dial")) == Some(FeatureState::Available)+ })+}+fn key(device: DeviceId, call: &str) -> String {format!("{device} {call}")}pub fn on_event(event: &NodeEvent) {+ let page_device = page_state(|s| s.device);match event {- NodeEvent::Call { device, call } => changed(*device, call),+ NodeEvent::Call { device, call } => {+ changed(*device, call);+ if Some(*device) == page_device && call.state == "ended" {+ core_host::spawn(async move {+ tokio::time::sleep(std::time::Duration::from_millis(600)).await;+ load_call_log(None);+ });+ }+ }+ NodeEvent::CallLogChanged { device } if Some(*device) == page_device => {+ load_call_log(None);+ }+ NodeEvent::ContactsChanged { device } if Some(*device) == page_device => {+ load_contacts();+ }+ NodeEvent::LinkChanged { device, link: LinkState::Online { .. } } if Some(*device) == page_device => {+ if page_state(|s| s.log_status != Status::Ready) {+ load_call_log(None);+ }+ if page_state(|s| s.contacts_status != Status::Ready) {+ load_contacts();+ }+ }// 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);+ if Some(*device) == page_device {+ page_state(|s| {+ s.log_status = Status::Offline;+ s.contacts_status = Status::Offline;+ });+ core_host::host().hub.changed(Changes::CALLS);+ }}// 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)+ NodeEvent::Capabilities(matrix) => {+ if matrix.state("calls.control") == Some(FeatureState::Available)+ && let Some(call) = active(matrix.device)&& notified(|n| n.get(&matrix.device) != Some(&call.id)){show_in_progress(matrix.device, &call);}+ if Some(matrix.device) == page_device {+ if matrix.state("calls.log") == Some(FeatureState::Available)+ && page_state(|s| !matches!(s.log_status, Status::Ready | Status::Loading))+ {+ load_call_log(None);+ }+ if matrix.state("contacts.read") == Some(FeatureState::Available)+ && page_state(|s| !matches!(s.contacts_status, Status::Ready | Status::Loading))+ {+ load_contacts();+ }+ }}_ => {}}@@ -315,6 +374,358 @@ pub fn on_toast(key: &str, action: &str) {});}+// ---- Calls page: call log, contacts and dialing ----++#[derive(Debug, Default)]+struct PageState {+ device: Option<DeviceId>,+ log_status: Status,+ log: Vec<CallLogEntry>,+ more_log: bool,+ loading_older: bool,+ contacts_status: Status,+ contacts: Vec<Contact>,+ dialing: bool,+ /// Caller photos saved, by call log entry ID.+ log_photos: HashMap<String, PathBuf>,+ /// Contact photos saved, by contact ID.+ contact_photos: HashMap<String, PathBuf>,+ /// Bumped when the phone changes, so late answers are dropped.+ generation: u64,+}++static PAGE: Mutex<Option<PageState>> = Mutex::new(None);++fn page_state<T>(f: impl FnOnce(&mut PageState) -> T) -> T {+ f(PAGE.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())+}++fn page_changed() {+ core_host::host().hub.changed(Changes::CALLS);+}++#[derive(Debug, Clone, PartialEq)]+pub struct View {+ pub device: Option<DeviceId>,+ pub log_status: Status,+ pub call_log: Value,+ pub more_log: bool,+ pub loading_older: bool,+ pub contacts_status: Status,+ pub contacts: Value,+ pub dialing: bool,+}++pub fn view() -> View {+ page_state(|s| {+ // Match call log numbers to contacts for photos and fallback names.+ let mut by_digits: HashMap<String, (&str, Option<&PathBuf>)> = HashMap::new();+ for c in &s.contacts {+ let photo = s.contact_photos.get(&c.id);+ for n in &c.numbers {+ let d = digits(&n.number);+ if !d.is_empty() {+ by_digits.entry(d).or_insert((c.name.as_str(), photo));+ }+ }+ }+ View {+ device: s.device,+ log_status: s.log_status,+ call_log: Value::Array(+ s.log+ .iter()+ .map(|e| {+ let matched = digits(&e.number);+ let from_contact =+ (!matched.is_empty()).then(|| by_digits.get(&matched).copied()).flatten();+ let photo = s+ .log_photos+ .get(&e.id)+ .or_else(|| from_contact.and_then(|(_, p)| p))+ .map(|p| crate::icons::file_url(p))+ .unwrap_or_default();+ let name = e+ .name+ .as_deref()+ .filter(|n| !n.trim().is_empty())+ .or_else(|| from_contact.map(|(n, _)| n).filter(|n| !n.trim().is_empty()))+ .unwrap_or_default();+ log_entry_json(e, name, photo)+ })+ .collect(),+ ),+ more_log: s.more_log,+ loading_older: s.loading_older,+ contacts_status: s.contacts_status,+ contacts: Value::Array(+ s.contacts.iter().map(|c| contact_json(c, s.contact_photos.get(&c.id))).collect(),+ ),+ dialing: s.dialing,+ }+ })+}++fn log_entry_json(e: &CallLogEntry, name: &str, photo: String) -> Value {+ json!({+ "id": e.id,+ "number": e.number,+ "name": name,+ "photo": photo,+ "direction": e.direction,+ "date": e.date,+ "duration": e.duration,+ })+}++fn contact_json(c: &Contact, photo: Option<&PathBuf>) -> Value {+ let numbers: Vec<Value> = c+ .numbers+ .iter()+ .map(|n| {+ json!({+ "number": n.number,+ "label": n.label.clone().unwrap_or_default(),+ })+ })+ .collect();+ json!({+ "id": c.id,+ "name": c.name,+ "numbers": numbers,+ "starred": c.starred,+ "photo": photo.map(|p| crate::icons::file_url(p)).unwrap_or_default(),+ })+}++/// Shows `device`'s call log and contacts (again: reloads).+pub fn open_device(device: DeviceId) {+ let same = page_state(|s| {+ let same = s.device == Some(device);+ if !same {+ *s = PageState { device: Some(device), generation: s.generation + 1, ..PageState::default() };+ }+ same+ });+ if !same {+ page_changed();+ }+ load_call_log(None);+ load_contacts();+}++/// Loads `device`'s contacts in the background if not already loaded for it+/// (used by Messages' recipient autocomplete).+pub fn ensure_contacts(device: DeviceId) {+ let should_load = page_state(|s| {+ if s.device != Some(device) {+ *s = PageState { device: Some(device), generation: s.generation + 1, ..PageState::default() };+ true+ } else {+ s.contacts.is_empty() && s.contacts_status != Status::Loading+ }+ });+ if should_load {+ load_contacts();+ }+}++pub fn reload() {+ load_call_log(None);+ load_contacts();+}++pub fn load_older() {+ let before = page_state(|s| {+ if s.loading_older || !s.more_log {+ return None;+ }+ s.loading_older = true;+ s.log.last().map(|e| e.date)+ });+ if before.is_some() {+ page_changed();+ load_call_log(before);+ }+}++fn load_call_log(before: Option<i64>) {+ let Some((device, generation)) = page_state(|s| {+ if before.is_none() && s.log.is_empty() {+ s.log_status = Status::Loading;+ }+ s.device.map(|d| (d, s.generation))+ }) else {+ return;+ };+ page_changed();+ let Some(node) = core_host::node() else { return };+ core_host::spawn(async move {+ let result = node.call_log(device, before, LOG_PAGE).await;+ let photos = match &result {+ Ok(entries) => save_log_photos(device, entries),+ Err(_) => HashMap::new(),+ };+ page_state(|s| {+ s.loading_older = false;+ if s.generation != generation {+ return;+ }+ match result {+ Ok(page) => {+ let full = page.len() as u32 >= LOG_PAGE;+ if before.is_none() {+ let oldest = page.last().map(|e| e.date).unwrap_or(i64::MAX);+ let older: Vec<CallLogEntry> = s.log.drain(..).filter(|e| e.date < oldest).collect();+ let had_older = !older.is_empty();+ s.log = page;+ s.log.extend(older);+ s.more_log = full || (had_older && s.more_log);+ } else {+ s.log.extend(page);+ s.more_log = full;+ }+ s.log_photos.extend(photos);+ s.log_status = Status::Ready;+ }+ Err(e) => {+ tracing::debug!(error = %e, "can't read call log");+ s.log_status = Status::of(&e);+ }+ }+ });+ page_changed();+ });+}++fn load_contacts() {+ let Some((device, generation)) = page_state(|s| {+ if s.contacts.is_empty() {+ s.contacts_status = Status::Loading;+ }+ s.device.map(|d| (d, s.generation))+ }) else {+ return;+ };+ page_changed();+ let Some(node) = core_host::node() else { return };+ core_host::spawn(async move {+ let mut all = Vec::new();+ let mut err = None;+ for page in 0..MAX_CONTACT_PAGES {+ let offset = page * CONTACTS_PAGE;+ match node.contacts(device, None, offset, CONTACTS_PAGE).await {+ Ok(items) => {+ let full = items.len() as u32 >= CONTACTS_PAGE;+ all.extend(items);+ if !full {+ break;+ }+ }+ Err(e) => {+ if page == 0 {+ err = Some(e);+ }+ break;+ }+ }+ }+ let photos = if err.is_none() { save_contact_photos(device, &all) } else { HashMap::new() };+ page_state(|s| {+ if s.generation != generation {+ return;+ }+ match err {+ None => {+ s.contacts = all;+ s.contact_photos.extend(photos);+ s.contacts_status = Status::Ready;+ }+ Some(e) => {+ tracing::debug!(error = %e, "can't list contacts");+ s.contacts_status = Status::of(&e);+ }+ }+ });+ page_changed();+ });+}++fn save_log_photos(device: DeviceId, entries: &[CallLogEntry]) -> HashMap<String, PathBuf> {+ let dir = crate::notifications::images_dir();+ if std::fs::create_dir_all(&dir).is_err() {+ return HashMap::new();+ }+ entries+ .iter()+ .filter_map(|e| {+ let photo = e.photo.as_ref()?;+ let path = dir.join(format!(+ "call-log-{:016x}.jpg",+ crate::photos::fingerprint(&format!("{device} {}", e.id))+ ^ crate::photos::fingerprint_bytes(photo)+ ));+ if !path.exists() {+ std::fs::write(&path, photo).ok()?;+ }+ Some((e.id.clone(), path))+ })+ .collect()+}++fn save_contact_photos(device: DeviceId, contacts: &[Contact]) -> HashMap<String, PathBuf> {+ let dir = crate::notifications::images_dir();+ if std::fs::create_dir_all(&dir).is_err() {+ return HashMap::new();+ }+ contacts+ .iter()+ .filter_map(|c| {+ let photo = c.photo.as_ref()?;+ let path = dir.join(format!(+ "contact-{:016x}.jpg",+ crate::photos::fingerprint(&format!("{device} {}", c.id))+ ^ crate::photos::fingerprint_bytes(photo)+ ));+ if !path.exists() {+ std::fs::write(&path, photo).ok()?;+ }+ Some((c.id.clone(), path))+ })+ .collect()+}++/// Why a call couldn't be placed, for the user.+pub fn dial_problem(error: &Error) -> &'static str {+ match error {+ Error::Denied => "Calls are turned off for this phone.",+ Error::Unsupported => {+ "The phone doesn't place calls for this PC. Allow it in the Nectarlink app on the phone."+ }+ Error::Offline | Error::NotPaired | Error::Timeout => "The phone isn't connected.",+ _ => "The phone couldn't place that call.",+ }+}++/// Asks `device` to dial `number`.+pub fn dial(device: DeviceId, number: String) {+ let number = number.trim().to_owned();+ if number.is_empty() {+ return;+ }+ page_state(|s| s.dialing = true);+ page_changed();+ let Some(node) = core_host::node() else { return };+ core_host::spawn(async move {+ let result = node.call_dial(device, number).await;+ page_state(|s| s.dialing = false);+ page_changed();+ if let Err(e) = result {+ show_message(dial_problem(&e));+ }+ });+}+#[cfg(test)]mod tests {use super::*;@@ -339,4 +750,67 @@ mod tests {assert_eq!(caller(&call(Some(" "), Some("+1555"))), "+1555");assert_eq!(caller(&call(None, None)), "Unknown caller");}++ #[test]+ fn call_log_and_contacts_view_matches_numbers_and_formats_json() {+ use nectarlink_core::ContactNumber;++ page_state(|s| {+ *s = PageState {+ log_status: Status::Ready,+ contacts_status: Status::Ready,+ log: vec![+ CallLogEntry {+ id: "10".into(),+ number: "+1 (555) 010-1001".into(),+ name: None,+ photo: None,+ direction: "missed".into(),+ date: 1700000000000,+ duration: 0,+ },+ CallLogEntry {+ id: "9".into(),+ number: "+15550109999".into(),+ name: Some("Explicit Name".into()),+ photo: None,+ direction: "outgoing".into(),+ date: 1699990000000,+ duration: 95,+ },+ ],+ contacts: vec![Contact {+ id: "c1".into(),+ name: "Alice Rivera".into(),+ numbers: vec![ContactNumber {+ number: "555-010-1001".into(),+ label: Some("Mobile".into()),+ }],+ starred: true,+ photo: None,+ }],+ ..PageState::default()+ };+ });++ let v = view();+ assert_eq!(v.log_status, Status::Ready);+ assert_eq!(v.contacts_status, Status::Ready);+ let log = v.call_log.as_array().unwrap();+ assert_eq!(log.len(), 2);+ // Matched to Alice Rivera by trailing digits!+ assert_eq!(log[0]["name"], "Alice Rivera");+ assert_eq!(log[0]["direction"], "missed");+ assert_eq!(log[1]["name"], "Explicit Name");+ assert_eq!(log[1]["duration"], 95);++ let contacts = v.contacts.as_array().unwrap();+ assert_eq!(contacts.len(), 1);+ assert_eq!(contacts[0]["name"], "Alice Rivera");+ assert_eq!(contacts[0]["starred"], true);+ assert_eq!(contacts[0]["numbers"][0]["label"], "Mobile");++ assert_eq!(dial_problem(&Error::Denied), "Calls are turned off for this phone.");+ assert_eq!(dial_problem(&Error::Offline), "The phone isn't connected.");+ }}diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rsindex 5a712be..a1ea13e 100644--- a/desktop/app/src/core_host.rs+++ b/desktop/app/src/core_host.rs@@ -100,6 +100,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {"pc.power".into(),nectarlink_core::PHOTOS_SHOW.into(),nectarlink_core::CALLS_SHOW.into(),+ nectarlink_core::CONTACTS_SHOW.into(),nectarlink_core::SMS_SHOW.into(),nectarlink_core::MIRROR_VIEW.into(),nectarlink_core::MIRROR_LISTEN.into(),diff --git a/desktop/app/src/messages.rs b/desktop/app/src/messages.rsindex cdb5fb0..02762b6 100644--- a/desktop/app/src/messages.rs+++ b/desktop/app/src/messages.rs@@ -44,7 +44,7 @@ impl Status {}}- fn of(error: &Error) -> Status {+ pub(crate) fn of(error: &Error) -> Status {match error {Error::Denied => Status::Off,Error::Unsupported => Status::Unsupported,@@ -71,6 +71,9 @@ struct State {pictures: HashMap<String, PathBuf>,/// Contact photos saved, by thread ID.photos: HashMap<String, PathBuf>,+ /// A number pre-filled in the new-message box (from Calls / Contacts).+ compose_to: Option<String>,+ compose_name: Option<String>,/// Bumped when the phone changes, so late answers are dropped.generation: u64,}@@ -102,6 +105,8 @@ pub struct View {pub more: bool,pub loading_older: bool,pub sending: bool,+ pub compose_to: Option<String>,+ pub compose_name: Option<String>,}pub fn view() -> View {@@ -125,6 +130,8 @@ pub fn view() -> View {more: s.more,loading_older: s.loading_older,sending: s.sending,+ compose_to: s.compose_to.clone(),+ compose_name: s.compose_name.clone(),})}@@ -307,6 +314,8 @@ fn save_photos(device: DeviceId, threads: &[SmsThread]) -> HashMap<String, PathB/// Opens a conversation: its latest messages.pub fn open_thread(thread: String) {state(|s| {+ s.compose_to = None;+ s.compose_name = None;if s.thread.as_deref() != Some(&thread) {s.thread = Some(thread);s.messages.clear();@@ -317,6 +326,50 @@ pub fn open_thread(thread: String) {load_messages(None);}+/// Opens an existing 1-on-1 conversation with `number` on `device`, or starts+/// a new one with `number` pre-filled.+pub fn start_chat(device: DeviceId, number: String, name: String) {+ let number = number.trim().to_owned();+ if number.is_empty() {+ return;+ }+ let name = name.trim().to_owned();+ let wanted = digits(&number);+ let existing = state(|s| {+ if s.device != Some(device) {+ *s = State { device: Some(device), generation: s.generation + 1, ..State::default() };+ }+ let found = (!wanted.is_empty()).then(|| {+ s.threads+ .iter()+ .find(|t| t.addresses.len() == 1 && digits(&t.addresses[0]) == wanted)+ .map(|t| t.id.clone())+ })?;+ if found.is_none() {+ s.thread = None;+ s.messages.clear();+ s.more = false;+ s.compose_to = Some(number.clone());+ s.compose_name = (!name.is_empty() && name != number).then_some(name);+ } else {+ s.compose_to = None;+ s.compose_name = None;+ }+ found+ });+ if let Some(thread) = existing {+ PENDING_OPEN.lock().unwrap_or_else(|e| e.into_inner()).take();+ open_thread(thread);+ load_threads();+ } else {+ if !wanted.is_empty() {+ PENDING_OPEN.lock().unwrap_or_else(|e| e.into_inner()).replace(vec![wanted]);+ }+ changed();+ load_threads();+ }+}+/// The open conversation's older messages.pub fn load_older() {let before = state(|s| {@@ -445,6 +498,8 @@ pub fn send_to(to: Vec<String>, body: String) {let local_id = format!("local:{now}:{}", NEXT_LOCAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed));let Some(device) = state(|s| {s.sending = true;+ s.compose_to = None;+ s.compose_name = None;// Shown at once as "Sending…"; the phone's copy replaces it.if let Some(thread) = s.thread.clone() {s.messages.insert(@@ -507,7 +562,7 @@ fn reload_after_send(to: &[String]) {static PENDING_OPEN: Mutex<Option<Vec<String>>> = Mutex::new(None);/// The last digits of a number, to match "+1 555-0100" with "5550100".-fn digits(number: &str) -> String {+pub(crate) fn digits(number: &str) -> String {let all: String = number.chars().filter(char::is_ascii_digit).collect();all[all.len().saturating_sub(9)..].to_owned()}@@ -522,8 +577,11 @@ pub fn reload() {/// Closes the open conversation (for writing a new one).pub fn close_thread() {+ PENDING_OPEN.lock().unwrap_or_else(|e| e.into_inner()).take();state(|s| {s.thread = None;+ s.compose_to = None;+ s.compose_name = None;s.messages.clear();s.more = false;});diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rsindex ea44727..d8d30c9 100644--- a/desktop/app/src/state.rs+++ b/desktop/app/src/state.rs@@ -392,6 +392,8 @@ impl AppState {NodeEvent::ClipboardReceived { .. }| NodeEvent::PhotoAdded { .. }| NodeEvent::Call { .. }+ | NodeEvent::CallLogChanged { .. }+ | NodeEvent::ContactsChanged { .. }| NodeEvent::SmsChanged { .. }| NodeEvent::Mirroring { .. } => Changes::NONE,NodeEvent::Transfer(transfer) => self.update_transfer(transfer.clone(), Instant::now()),diff --git a/docs/protocol/calls.md b/docs/protocol/calls.mdindex bad7b14..6309161 100644--- a/docs/protocol/calls.md+++ b/docs/protocol/calls.md@@ -4,10 +4,11 @@> 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, and+and when it ends. A PC can answer, decline or silence a ringing call,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.+the volume of the call in progress, browse recent calls, and ask the phone+to call a number. The call's audio stays on the phone; this service+carries no sound.## 1. Capabilities@@ -16,11 +17,13 @@ this service carries no sound.| `call.state` | phone | Reports its calls (needs the phone permission) || `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 |+| `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.show` | PC | Shows calls, recent calls and the dialer, and wants `call.log.changed` |-A phone reports calls only to PCs that offer `call.show`, and only while-both devices allow it (the `calls` device toggle, on by default, on each-side).+A phone reports calls and answers call requests only for PCs that offer+`call.show`, and only while both devices allow it (the `calls` device+toggle, on by default, on each side).## 2. Messages@@ -51,6 +54,24 @@ t = "call.action" id = n b = {? digit: text, // With "dtmf": one of 0–9, * and #}t = "ok" re = n++t = "call.log" id = n b = { ? before: int, limit: uint } // 1–100+t = "call.log" re = n b = { entries: [ call_entry ] } // newest first++t = "call.log.changed" b = {} // phone → PC++t = "call.dial" id = n b = { number: text }+t = "ok" re = n++call_entry = {+ id: text,+ number: text, // Who called, or who was called ("" when withheld)+ ? name: text, // The contact's name, when the number is a contact+ direction: "incoming" | "outgoing" | "missed" | "rejected",+ date: int, // When the call started, in Unix milliseconds+ duration: uint, // Seconds on the call (0 when missed or not answered)+ ? photo: bytes, // The contact's photo, a JPEG of at most 16 KiB+}```### 2.1 `call.state`@@ -83,11 +104,40 @@ except `decline`, need it active); `DENIED` when calls are off for the PC;`UNSUPPORTED` for an unknown action, a `dtmf` without a valid `digit`, orwhen the phone doesn't offer the capability the action needs.-### 2.3 On Android+### 2.3 `call.log` and `call.log.changed`++`call.log` pages back through the phone's recent calls, newest first:+`before` is the oldest `date` already shown. A phone answers with fewer+items than `limit` when the answer wouldn't fit in a frame (v0 §3),+dropping the oldest.++The phone sends `call.log.changed` to connected PCs that offer `call.show`+when its call log changes (debounced). PCs then ask again for what they+show.++Errors: `DENIED` when calls are off for the PC, `UNSUPPORTED` when the+phone doesn't offer `call.log`.++### 2.4 `call.dial`++`call.dial` asks the phone to call `number` (1–256 bytes, not blank). With+`CALL_PHONE` permission the phone places the call directly+(`Intent.ACTION_CALL`); if that permission isn't granted, it opens the+dialer (`Intent.ACTION_DIAL`) with the number filled in. Once the call+starts, the phone reports it through `call.state`, so the PC's call card+and in-call controls work as for any call.++Errors: `DENIED` when calls are off for the PC, `UNSUPPORTED` when the+phone doesn't offer `call.dial`, `INTERNAL` when the phone couldn't start+the call.++### 2.5 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+calls. `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+the `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(Wireless debugging) grants it through the shell when it starts.diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.mdindex d360217..03d7626 100644--- a/docs/protocol/capabilities.md+++ b/docs/protocol/capabilities.md@@ -39,6 +39,9 @@ capability is missing.| `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+ |+| `call.log` | Lists recent calls ([calls](calls.md)) | phone permission |+| `call.dial` | Places a call or opens the dialer when a PC asks ([calls](calls.md)) | phone permission |+| `contacts.read` | Lists and searches contacts ([contacts](contacts.md)) | contacts permission || `clip.write` | Accepts clipboard content from the PC ([clipboard service](clipboard.md)) | app update || `clip.share` | Sends the clipboard when the user taps "Send" | app update || `clip.read.auto` | Sends clipboard changes automatically, in the background | Elevated |@@ -56,7 +59,8 @@ capability is missing.|---|---|---|| `pc.power` | Locks or sleeps on request ([actions](actions.md)) | app update || `photos.show` | Shows a phone's new photos ([photos](photos.md)) | app update |-| `call.show` | Shows a phone's calls ([calls](calls.md)) | app update |+| `call.show` | Shows a phone's calls, recent calls and dialer ([calls](calls.md)) | app update |+| `contacts.show` | Shows a phone's contacts ([contacts](contacts.md)) | app update || `sms.show` | Shows a phone's text messages ([messages](sms.md)) | app update || `mirror.view` | Shows a phone's screen ([mirroring](mirror.md)) | app update || `mirror.listen` | Plays a mirrored phone's sound ([mirroring](mirror.md)) | app update |diff --git a/docs/protocol/contacts.md b/docs/protocol/contacts.mdnew file mode 100644index 0000000..73cfd62--- /dev/null+++ b/docs/protocol/contacts.md@@ -0,0 +1,68 @@+# Contacts service (protocol v0)++> Status: **draft.** Builds on [protocol v0](v0.md); breaking changes are+> allowed until v1. License: CC BY 4.0.++A PC browses and searches a phone's contacts to call or text them from the+PC. The phone keeps the contacts; a PC asks for them on demand and keeps+them only in memory.++## 1. Capabilities++| ID | Offered by | Meaning |+|---|---|---|+| `contacts.read` | phone | Lists and searches contacts (needs the contacts permission) |+| `contacts.show` | PC | Shows contacts, and wants `contacts.changed` |++Both devices must allow it: the `contacts` device toggle, on by default,+on each side.++## 2. Messages++On the control stream. Each request is answered with the matching answer+or `error`.++```+t = "contacts.list" id = n b = { ? query: text, ? offset: uint, limit: uint } // limit 1–200+t = "contacts.list" re = n b = { contacts: [ contact ] }++t = "contacts.changed" b = {} // phone → PC++contact = {+ id: text,+ name: text,+ numbers: [ { number: text, ? label: text } ], // 1–16 phone numbers+ ? starred: bool, // Favorite contact (default false)+ ? photo: bytes, // Small JPEG, at most 16 KiB+}+```++### 2.1 Listing and searching++`contacts.list` returns contacts that have at least one phone number,+ordered with favorites (`starred: true`) first and then alphabetically by+`name`.++- `query` (optional, at most 256 bytes): when non-empty, filters to+ contacts whose `name` or any `number` matches `query` (case-insensitive;+ digits are also matched ignoring formatting).+- `offset` (optional, default `0`): skips the first `offset` matching+ contacts for paging.+- `limit` (`1..=200`): the most contacts to return in this page.++A phone answers with fewer items than `limit` when the answer wouldn't fit+in a frame (v0 §3), dropping from the end of the page. The PC advances+`offset` by the number of contacts received to fetch the next page.++Errors: `DENIED` when contacts are off for the PC, `UNSUPPORTED` when the+phone doesn't offer `contacts.read`.++### 2.2 Changes++The phone sends `contacts.changed` to connected PCs that offer+`contacts.show` when its contacts store changes (debounced). PCs then ask+again for what they show.++## 3. Privacy++Names, numbers and photos are never logged (v0 §11).