Modern Apps git

← Modern-Apps.git

communicate: surface WhatsApp and Signal calls via Telecom and a shared call screen

Commit
1453e7116cbadc1fb69c7d6d259b8bd9fa9f959e
Author
vayun-mathur <[email protected]>
When
2026-08-22 22:40 UTC (3 months ago)
Parents
14294bd

Diff

communicate/src/main/AndroidManifest.xml
diff --git a/communicate/src/main/AndroidManifest.xml b/communicate/src/main/AndroidManifest.xmlindex 32dff1e10f..9d5eb1f1a4 100644--- a/communicate/src/main/AndroidManifest.xml+++ b/communicate/src/main/AndroidManifest.xml@@ -167,6 +167,22 @@             android:exported="false"             android:foregroundServiceType="phoneCall" /> +        <!-- Shared self-managed Telecom account for WhatsApp and Signal calls, so the system owns+             ringing, call audio focus and Bluetooth routing rather than the app approximating them. -->+        <service+            android:name=".telephony.InAppCallConnectionService"+            android:exported="true"+            android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE">+            <intent-filter>+                <action android:name="android.telecom.ConnectionService" />+            </intent-filter>+        </service>++        <service+            android:name=".telephony.InAppCallForegroundService"+            android:exported="false"+            android:foregroundServiceType="phoneCall" />+         <provider             android:name="androidx.core.content.FileProvider"             android:authorities="${applicationId}.mmsfileprovider"
communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.ktindex 4e63d8a275..b1c1ec00e1 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt@@ -36,7 +36,12 @@ import com.vayunmathur.communicate.ui.CallLogsScreen import com.vayunmathur.communicate.ui.ConversationScreen import com.vayunmathur.communicate.ui.DialerScreen import com.vayunmathur.communicate.ui.MessagesScreen+import com.vayunmathur.communicate.data.call.InAppCallPhase+import com.vayunmathur.communicate.data.call.InAppCallRegistry+import com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallBridge+import com.vayunmathur.communicate.telephony.InAppCallTelecom import com.vayunmathur.communicate.ui.call.CallScreen+import com.vayunmathur.communicate.ui.call.InAppCallScreen import com.vayunmathur.communicate.ui.googlevoice.GoogleVoiceSignInScreen import com.vayunmathur.communicate.ui.whatsapp.WhatsAppRegistrationScreen import com.vayunmathur.communicate.telephony.WhatsAppSyncService@@ -103,6 +108,7 @@ private fun CommunicateApp() {     val sigSession = remember { SignalLineSession.get(context) }     val sigSignedIn by sigSession.signedInFlow.collectAsState(initial = false)     val callState by GoogleVoiceCallManager.state.collectAsState()+    val inAppCallState by InAppCallRegistry.state.collectAsState()      // Own the WhatsApp always-on receive state via its foreground sync service (dev-only).     LaunchedEffect(waSignedIn) {@@ -129,6 +135,21 @@ private fun CommunicateApp() {         }     } +    // WhatsApp and Signal calls share one Telecom account and one call screen. Registered whenever either+    // line is usable, so the system owns ringing and audio routing rather than the app approximating it.+    LaunchedEffect(waSignedIn, sigSignedIn) {+        val anyLine = (com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled && waSignedIn) ||+            (SignalFeature.enabled && sigSignedIn)+        if (anyLine) {+            InAppCallTelecom.registerPhoneAccount(context, context.getString(R.string.app_name))+            if (com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) {+                WhatsAppCallBridge.ensureStarted(context)+            }+        } else {+            InAppCallTelecom.unregisterPhoneAccount(context)+        }+    }+     val backStack = rememberNavBackStack<Route>(Route.Main)      MainNavigation(backStack) {@@ -197,6 +218,10 @@ private fun CommunicateApp() {     // In-app call UI overlays everything while a Google Voice VoIP call is in progress.     if (callState.phase != CallPhase.Idle) {         CallScreen(onClose = { GoogleVoiceCallManager.clearEnded() })+    } else if (inAppCallState.phase != InAppCallPhase.Idle) {+        // WhatsApp and Signal share one screen. Google Voice wins a tie: it is a Telecom-owned call that+        // was already on screen.+        InAppCallScreen(onClose = { InAppCallRegistry.clearEnded() })     } } 
communicate/src/main/java/com/vayunmathur/communicate/data/call/InAppCall.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/call/InAppCall.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/call/InAppCall.ktnew file mode 100644index 0000000000..f00873ef49--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/call/InAppCall.kt@@ -0,0 +1,153 @@+package com.vayunmathur.communicate.data.call++import com.vayunmathur.communicate.data.CommunicateLine+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/** Phases an in-app VoIP call moves through, shared by every line that isn't handled by the SIM. */+enum class InAppCallPhase { Idle, Outgoing, Incoming, Connecting, Active, Ended }++/**+ * The single active in-app call, in the shape the UI and the Telecom bridge need.+ *+ * Deliberately richer than what the underlying stacks expose: RingRTC reports only+ * ringing/connecting/connected and drops the call id on most callbacks, so mute, speaker, the peer's+ * name and the connect time have to be tracked here or the UI has nothing to show.+ */+data class InAppCallState(+    val phase: InAppCallPhase = InAppCallPhase.Idle,+    val line: CommunicateLine? = null,+    /** Line-specific id (ACI, JID) used to address call actions. */+    val peerId: String = "",+    val peerName: String = "",+    val isVideo: Boolean = false,+    val muted: Boolean = false,+    val speaker: Boolean = false,+    /** When the call became [InAppCallPhase.Active], for the duration readout. 0 until then. */+    val connectedAtMs: Long = 0L,+    val endReason: String? = null,+) {+    val isRinging: Boolean get() = phase == InAppCallPhase.Incoming+    val isOngoing: Boolean get() = phase == InAppCallPhase.Active || phase == InAppCallPhase.Connecting+}++/**+ * What the call UI and the system call surface can do to a call, implemented per line.+ *+ * Kept minimal on purpose: anything a line cannot do is a no-op rather than an error, so the shared+ * screen does not need to know which line it is driving.+ */+interface InAppCallController {+    fun answer()+    fun reject()+    fun hangup()+    fun setMuted(muted: Boolean)+    fun setSpeaker(on: Boolean)+}++/** Implemented by the Telecom `Connection` so a line's manager can drive the system call surface. */+interface InAppCallConnectionBridge {+    fun onCallActive()+    fun onCallEnded()+}++/**+ * The one place that knows whether a call is up, regardless of line.+ *+ * A single registry rather than one per line because only one in-app call can be active at a time, and+ * because the call screen, the notification and the Telecom connection all need the same view of it.+ * Google Voice deliberately stays outside this: it already has its own Telecom integration.+ */+object InAppCallRegistry {+    private val _state = MutableStateFlow(InAppCallState())+    val state: StateFlow<InAppCallState> = _state.asStateFlow()++    @Volatile+    private var controller: InAppCallController? = null++    /** Set by the Telecom ConnectionService so state changes can be reflected into the system UI. */+    @Volatile+    var connection: InAppCallConnectionBridge? = null++    fun bind(line: CommunicateLine, controller: InAppCallController) {+        this.controller = controller+        _state.value = _state.value.copy(line = line)+    }++    /** Called by a line when its call starts, so the UI can appear before any media is up. */+    fun onCallStarting(+        line: CommunicateLine,+        peerId: String,+        peerName: String,+        isVideo: Boolean,+        incoming: Boolean,+    ) {+        _state.value = InAppCallState(+            phase = if (incoming) InAppCallPhase.Incoming else InAppCallPhase.Outgoing,+            line = line,+            peerId = peerId,+            peerName = peerName.ifBlank { peerId },+            isVideo = isVideo,+        )+    }++    fun onPhase(phase: InAppCallPhase) {+        val current = _state.value+        if (current.phase == InAppCallPhase.Idle && phase != InAppCallPhase.Incoming) return+        _state.value = current.copy(+            phase = phase,+            // Stamped once, on the transition into Active, so the duration does not restart.+            connectedAtMs = if (phase == InAppCallPhase.Active && current.connectedAtMs == 0L) {+                System.currentTimeMillis()+            } else {+                current.connectedAtMs+            },+        )+        if (phase == InAppCallPhase.Active) connection?.onCallActive()+    }++    fun onEnded(reason: String?) {+        val current = _state.value+        if (current.phase == InAppCallPhase.Idle) return+        _state.value = current.copy(phase = InAppCallPhase.Ended, endReason = reason)+        connection?.onCallEnded()+    }++    fun onMuted(muted: Boolean) {+        _state.value = _state.value.copy(muted = muted)+    }++    fun onSpeaker(on: Boolean) {+        _state.value = _state.value.copy(speaker = on)+    }++    /** Called by the UI once a terminal state has been shown, returning to Idle. */+    fun clearEnded() {+        if (_state.value.phase == InAppCallPhase.Ended) {+            _state.value = InAppCallState()+            controller = null+            connection = null+        }+    }++    // -- Actions, forwarded to whichever line owns the call --++    fun answer() = controller?.answer() ?: Unit++    fun reject() = controller?.reject() ?: Unit++    fun hangup() = controller?.hangup() ?: Unit++    fun toggleMuted() {+        val next = !_state.value.muted+        controller?.setMuted(next)+        onMuted(next)+    }++    fun toggleSpeaker() {+        val next = !_state.value.speaker+        controller?.setSpeaker(next)+        onSpeaker(next)+    }+}
communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.ktindex b42d08f11a..68bafe15c9 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/SignalClient.kt@@ -4,6 +4,10 @@ import android.content.Context import android.util.Base64 as AndroidBase64 import android.util.Log import com.vayunmathur.communicate.data.signal.e2e.SignalE2E+import com.vayunmathur.communicate.data.CommunicateLine+import com.vayunmathur.communicate.data.call.InAppCallController+import com.vayunmathur.communicate.data.call.InAppCallPhase+import com.vayunmathur.communicate.data.call.InAppCallRegistry import com.vayunmathur.communicate.data.signal.call.SignalCallManager import com.vayunmathur.communicate.data.signal.call.SignalCallMessage import com.vayunmathur.communicate.data.signal.call.toContent@@ -14,6 +18,7 @@ import com.vayunmathur.communicate.data.signal.transport.SignalKeysApi import com.vayunmathur.communicate.data.signal.transport.SignalPayload import com.vayunmathur.communicate.data.signal.transport.SignalSocket import com.vayunmathur.communicate.data.signal.transport.SignalTrust+import com.vayunmathur.communicate.telephony.InAppCallTelecom import org.signal.libsignal.metadata.certificate.SenderCertificate import org.signal.libsignal.protocol.IdentityKey import org.signal.libsignal.protocol.UntrustedIdentityException@@ -401,6 +406,16 @@ object SignalClient {     /** Guards against overlapping discovery runs; `start()` can fire more than once. */     private val discoveryRunning = AtomicBoolean(false) +    /**+     * The inbound call awaiting an answer. RingRTC reports `Ringing` for both directions, so this is what+     * distinguishes an incoming call and supplies the id [InAppCallController.answer] needs.+     */+    @Volatile+    private var pendingIncomingCallAci: String? = null++    @Volatile+    private var pendingIncomingCallId: Long? = null+     /** Same reason as [discoveryRunning]: without it, each start generates and uploads another batch. */     private val preKeysPrepared = AtomicBoolean(false) @@ -1238,7 +1253,10 @@ object SignalClient {                     state: SignalCallManager.CallState,                     isVideo: Boolean,                 ) {-                    scope.launch { emitCallState(aci, callId, state, isVideo) }+                    scope.launch {+                        publishCallState(aci, callId, state, isVideo)+                        emitCallState(aci, callId, state, isVideo)+                    }                 }             },             sslSocketFactory = { signalTls() },@@ -1272,6 +1290,10 @@ object SignalClient {             cm.hasOffer() -> {                 val offer = cm.offer                 val isVideo = offer.type == SignalServiceProtos.CallMessage.Offer.Type.OFFER_VIDEO_CALL+                // Recorded before RingRTC reports Ringing, which is how the shared registry tells an+                // inbound call from an outbound one, and what `answer()` needs.+                pendingIncomingCallAci = senderAci+                pendingIncomingCallId = offer.id                 _events.emit(                     SignalEvent.CallOffer(                         callId = offer.id.toString(),@@ -1282,6 +1304,8 @@ object SignalClient {                         timestamp = timestamp,                     ),                 )+                // Hand the call to the system so it owns ringing, audio focus and routing.+                appContext?.let { ctx -> InAppCallTelecom.addIncoming(ctx, senderAci) }                 // Age matters: RingRTC drops offers that sat in the queue too long to still be ringing.                 val ageSec = ((env.serverTimestamp - env.timestamp).coerceAtLeast(0L)) / 1000                 manager.receivedOffer(@@ -1328,6 +1352,71 @@ object SignalClient {         }     } +    /**+     * Mirror RingRTC's state into the shared call registry, which is what the call screen and the system+     * call surface read. Registered lazily on the first state change so the controller is bound before the+     * UI can act on it.+     */+    private suspend fun publishCallState(+        aci: String,+        callId: Long,+        state: SignalCallManager.CallState,+        isVideo: Boolean,+    ) {+        val current = InAppCallRegistry.state.value+        if (current.phase == InAppCallPhase.Idle && state != SignalCallManager.CallState.Ended) {+            InAppCallRegistry.bind(CommunicateLine.Signal, signalCallController)+            InAppCallRegistry.onCallStarting(+                line = CommunicateLine.Signal,+                peerId = aci,+                peerName = displayNameFor(aci),+                isVideo = isVideo,+                // RingRTC reports Ringing for both directions; an inbound call already has an offer+                // recorded, which is how we tell them apart.+                incoming = pendingIncomingCallAci == aci,+            )+        }+        when (state) {+            SignalCallManager.CallState.Ringing ->+                if (pendingIncomingCallAci == aci) {+                    InAppCallRegistry.onPhase(InAppCallPhase.Incoming)+                } else {+                    InAppCallRegistry.onPhase(InAppCallPhase.Outgoing)+                }+            SignalCallManager.CallState.Connecting -> InAppCallRegistry.onPhase(InAppCallPhase.Connecting)+            SignalCallManager.CallState.Connected -> InAppCallRegistry.onPhase(InAppCallPhase.Active)+            SignalCallManager.CallState.Ended -> {+                InAppCallRegistry.onEnded(null)+                pendingIncomingCallAci = null+            }+        }+    }++    /** Bridges the shared call UI and the system call surface onto RingRTC. */+    private val signalCallController = object : InAppCallController {+        override fun answer() {+            val id = pendingIncomingCallId ?: return+            callManager?.accept(id)+        }++        override fun reject() {+            callManager?.hangup()+        }++        override fun hangup() {+            callManager?.hangup()+        }++        override fun setMuted(muted: Boolean) {+            // RingRTC's flag is "audio enabled", the inverse of muted.+            callManager?.setAudioEnabled(!muted)+        }++        override fun setSpeaker(on: Boolean) {+            // Routing belongs to Telecom while a self-managed connection is active; nothing to do here.+        }+    }+     private suspend fun emitCallState(         aci: String,         callId: Long,@@ -1388,6 +1477,8 @@ object SignalClient {                 return@launch             }             manager.placeCall(localAci, authData?.deviceId ?: PRIMARY_DEVICE_ID, resolved, video)+            // Mirror the call into the system so it owns audio focus and routing.+            appContext?.let { ctx -> InAppCallTelecom.addOutgoing(ctx, resolved) }         }     } 
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallBridge.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallBridge.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallBridge.ktnew file mode 100644index 0000000000..3ad0b91d1e--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallBridge.kt@@ -0,0 +1,85 @@+package com.vayunmathur.communicate.data.whatsapp.call++import android.content.Context+import com.vayunmathur.communicate.data.CommunicateLine+import com.vayunmathur.communicate.data.call.InAppCallController+import com.vayunmathur.communicate.data.call.InAppCallPhase+import com.vayunmathur.communicate.data.call.InAppCallRegistry+import com.vayunmathur.communicate.telephony.InAppCallTelecom+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import java.util.concurrent.atomic.AtomicBoolean++/**+ * Mirrors [WhatsAppCallManager]'s state into the shared [InAppCallRegistry] and hands calls to Telecom.+ *+ * An observer rather than a change inside the manager: its call flow already works, and the shared UI only+ * needs a projection of the state it already publishes.+ */+object WhatsAppCallBridge {+    private val started = AtomicBoolean(false)+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)++    /** Idempotent; safe to call from both the activity and the sync service. */+    fun ensureStarted(context: Context) {+        if (!started.compareAndSet(false, true)) return+        val appContext = context.applicationContext+        scope.launch {+            var lastPhase: WhatsAppCallPhase? = null+            WhatsAppCallManager.state.collect { state ->+                if (state.phase == lastPhase) return@collect+                val previous = lastPhase+                lastPhase = state.phase++                when (state.phase) {+                    WhatsAppCallPhase.Outgoing -> {+                        InAppCallRegistry.bind(CommunicateLine.WhatsApp, controller)+                        InAppCallRegistry.onCallStarting(+                            line = CommunicateLine.WhatsApp,+                            peerId = state.peerJid,+                            peerName = state.peerName.ifBlank { state.peerJid },+                            isVideo = state.isVideo,+                            incoming = false,+                        )+                        InAppCallTelecom.addOutgoing(appContext, state.peerJid)+                    }+                    WhatsAppCallPhase.Incoming -> {+                        InAppCallRegistry.bind(CommunicateLine.WhatsApp, controller)+                        InAppCallRegistry.onCallStarting(+                            line = CommunicateLine.WhatsApp,+                            peerId = state.peerJid,+                            peerName = state.peerName.ifBlank { state.peerJid },+                            isVideo = state.isVideo,+                            incoming = true,+                        )+                        InAppCallTelecom.addIncoming(appContext, state.peerJid)+                    }+                    WhatsAppCallPhase.Connecting -> InAppCallRegistry.onPhase(InAppCallPhase.Connecting)+                    WhatsAppCallPhase.Active -> InAppCallRegistry.onPhase(InAppCallPhase.Active)+                    WhatsAppCallPhase.Ended -> InAppCallRegistry.onEnded(null)+                    WhatsAppCallPhase.Idle ->+                        // Only meaningful as a return to rest after a call, not at startup.+                        if (previous != null) InAppCallRegistry.clearEnded()+                }+                if (state.phase != WhatsAppCallPhase.Idle) {+                    InAppCallRegistry.onMuted(state.muted)+                    InAppCallRegistry.onSpeaker(state.speaker)+                }+            }+        }+    }++    private val controller = object : InAppCallController {+        override fun answer() = WhatsAppCallManager.answer()++        override fun reject() = WhatsAppCallManager.reject()++        override fun hangup() = WhatsAppCallManager.hangup()++        override fun setMuted(muted: Boolean) = WhatsAppCallManager.setMuted(muted)++        override fun setSpeaker(on: Boolean) = WhatsAppCallManager.setSpeaker(on)+    }+}
communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.ktnew file mode 100644index 0000000000..e21caca567--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallForegroundService.kt@@ -0,0 +1,173 @@+package com.vayunmathur.communicate.telephony++import android.app.Notification+import android.app.NotificationManager+import android.app.PendingIntent+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.os.Build+import android.os.IBinder+import androidx.core.app.ServiceCompat+import androidx.core.content.ContextCompat+import com.vayunmathur.communicate.MainActivity+import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.call.InAppCallPhase+import com.vayunmathur.communicate.data.call.InAppCallRegistry+import com.vayunmathur.library.util.ensureNotificationChannel+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch++/**+ * Keeps a WhatsApp or Signal call alive off-screen — its socket, mic capture and process — and shows the+ * call notification. Started by [InAppCallConnectionService] and self-stops on a terminal state.+ *+ * Audio focus and audio mode are not handled here: the self-managed Telecom connection sets+ * `audioModeIsVoip`, so the system owns routing. Doing it in both places would fight.+ */+class InAppCallForegroundService : Service() {+    private val scope = CoroutineScope(SupervisorJob())+    private var observeJob: Job? = null++    override fun onBind(intent: Intent?): IBinder? = null++    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+        when (intent?.action) {+            ACTION_ANSWER -> InAppCallRegistry.answer()+            ACTION_HANGUP -> {+                if (InAppCallRegistry.state.value.phase == InAppCallPhase.Incoming) {+                    InAppCallRegistry.reject()+                } else {+                    InAppCallRegistry.hangup()+                }+            }+        }+        startForegroundWithNotification()+        observeJob?.cancel()+        observeJob = scope.launch {+            InAppCallRegistry.state.collect { state ->+                when (state.phase) {+                    InAppCallPhase.Idle, InAppCallPhase.Ended -> stopSelfSafely()+                    else -> startForegroundWithNotification()+                }+            }+        }+        return START_STICKY+    }++    private fun startForegroundWithNotification() {+        ensureChannels()+        val state = InAppCallRegistry.state.value+        val notification = if (state.phase == InAppCallPhase.Incoming) {+            buildIncomingCallNotification(state.peerName)+        } else {+            buildOngoingCallNotification(state.phase, state.peerName)+        }+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+            startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL)+        } else {+            startForeground(NOTIFICATION_ID, notification)+        }+    }++    private fun ensureChannels() {+        ensureNotificationChannel(CHANNEL_ID, getString(R.string.inapp_call_channel_name))+        ensureNotificationChannel(+            id = INCOMING_CHANNEL_ID,+            name = getString(R.string.inapp_incoming_call_channel_name),+            importance = NotificationManager.IMPORTANCE_HIGH,+            description = getString(R.string.inapp_incoming_call_channel_desc),+        ) {+            lockscreenVisibility = Notification.VISIBILITY_PUBLIC+        }+    }++    private fun buildIncomingCallNotification(peerName: String): Notification =+        Notification.Builder(this, INCOMING_CHANNEL_ID)+            .setContentTitle(getString(R.string.call_state_incoming_generic))+            .setContentText(peerName)+            .setSmallIcon(android.R.drawable.sym_call_incoming)+            .setCategory(Notification.CATEGORY_CALL)+            .setPriority(Notification.PRIORITY_MAX)+            .setVisibility(Notification.VISIBILITY_PUBLIC)+            .setOngoing(true)+            .setAutoCancel(false)+            .setContentIntent(callActivityIntent(0))+            .setFullScreenIntent(callActivityIntent(1), true)+            .addAction(+                android.R.drawable.sym_call_incoming,+                getString(R.string.call_answer),+                serviceActionIntent(ACTION_ANSWER, 2),+            )+            .addAction(+                android.R.drawable.ic_menu_close_clear_cancel,+                getString(R.string.call_decline),+                serviceActionIntent(ACTION_HANGUP, 3),+            )+            .build()++    private fun buildOngoingCallNotification(phase: InAppCallPhase, peerName: String): Notification {+        val title = when (phase) {+            InAppCallPhase.Outgoing -> getString(R.string.call_state_dialing)+            InAppCallPhase.Connecting -> getString(R.string.call_state_connecting)+            else -> getString(R.string.inapp_ongoing_call)+        }+        return Notification.Builder(this, CHANNEL_ID)+            .setContentTitle(title)+            .setContentText(peerName)+            .setSmallIcon(android.R.drawable.sym_action_call)+            .setCategory(Notification.CATEGORY_CALL)+            .setOngoing(true)+            .setContentIntent(callActivityIntent(0))+            .addAction(+                android.R.drawable.ic_menu_close_clear_cancel,+                getString(R.string.call_end),+                serviceActionIntent(ACTION_HANGUP, 3),+            )+            .build()+    }++    private fun serviceActionIntent(action: String, requestCode: Int): PendingIntent = PendingIntent.getService(+        this,+        requestCode,+        Intent(this, InAppCallForegroundService::class.java).apply { this.action = action },+        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+    )++    private fun callActivityIntent(requestCode: Int): PendingIntent = PendingIntent.getActivity(+        this,+        requestCode,+        Intent(this, MainActivity::class.java).apply {+            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)+        },+        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+    )++    private fun stopSelfSafely() {+        ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)+        stopSelf()+    }++    override fun onDestroy() {+        observeJob?.cancel()+        super.onDestroy()+    }++    companion object {+        private const val CHANNEL_ID = "inapp_calls"+        private const val INCOMING_CHANNEL_ID = "inapp_calls_incoming"+        private const val NOTIFICATION_ID = 4712++        private const val ACTION_ANSWER = "com.vayunmathur.communicate.inappcall.ANSWER_CALL"+        private const val ACTION_HANGUP = "com.vayunmathur.communicate.inappcall.HANGUP_CALL"++        fun start(context: Context) {+            ContextCompat.startForegroundService(+                context, Intent(context, InAppCallForegroundService::class.java),+            )+        }+    }+}
communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallTelecom.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallTelecom.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallTelecom.ktnew file mode 100644index 0000000000..b9dd04071b--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/InAppCallTelecom.kt@@ -0,0 +1,185 @@+package com.vayunmathur.communicate.telephony++import android.content.ComponentName+import android.content.Context+import android.net.Uri+import android.os.Bundle+import android.telecom.Connection+import android.telecom.ConnectionRequest+import android.telecom.ConnectionService+import android.telecom.DisconnectCause+import android.telecom.PhoneAccount+import android.telecom.PhoneAccountHandle+import android.telecom.TelecomManager+import android.telecom.VideoProfile+import com.vayunmathur.communicate.data.call.InAppCallConnectionBridge+import com.vayunmathur.communicate.data.call.InAppCallPhase+import com.vayunmathur.communicate.data.call.InAppCallRegistry++/**+ * Registers WhatsApp and Signal calling as one self-managed [PhoneAccount], so an in-app call behaves+ * like another line: the system owns the incoming-call surface, call audio focus, Bluetooth routing and+ * interruption handling, rather than the app approximating all of it.+ *+ * One account rather than one per line because only a single in-app call can be active at a time, and+ * [InAppCallRegistry] already knows which line owns it. Google Voice keeps its own account.+ */+object InAppCallTelecom {+    private const val ACCOUNT_ID = "communicate_inapp_calls"++    fun handle(context: Context): PhoneAccountHandle =+        PhoneAccountHandle(+            ComponentName(context.applicationContext, InAppCallConnectionService::class.java),+            ACCOUNT_ID,+        )++    fun registerPhoneAccount(context: Context, label: String) {+        val tm = context.getSystemService(TelecomManager::class.java) ?: return+        val account = PhoneAccount.builder(handle(context), label)+            .setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)+            .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)+            .addSupportedUriScheme(PhoneAccount.SCHEME_SIP)+            .build()+        runCatching { tm.registerPhoneAccount(account) }+    }++    fun unregisterPhoneAccount(context: Context) {+        val tm = context.getSystemService(TelecomManager::class.java) ?: return+        runCatching { tm.unregisterPhoneAccount(handle(context)) }+    }++    /**+     * Tell the system about a call the app has already started. The call itself is placed by the line;+     * Telecom is informed so it can own audio and the call surface.+     */+    fun addOutgoing(context: Context, peerId: String) {+        val tm = context.getSystemService(TelecomManager::class.java) ?: return+        val extras = Bundle().apply {+            putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, handle(context))+            // Self-managed calls must not be dialled by the system; we only mirror our own call.+            putBoolean(TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE, false)+        }+        val uri = Uri.fromParts(PhoneAccount.SCHEME_SIP, peerId, null)+        runCatching { tm.placeCall(uri, extras) }+    }++    fun addIncoming(context: Context, peerId: String) {+        val tm = context.getSystemService(TelecomManager::class.java) ?: return+        val extras = Bundle().apply {+            putParcelable(+                TelecomManager.EXTRA_INCOMING_CALL_ADDRESS,+                Uri.fromParts(PhoneAccount.SCHEME_SIP, peerId, null),+            )+        }+        runCatching { tm.addNewIncomingCall(handle(context), extras) }+    }+}++/**+ * The Telecom [Connection] for one in-app call. Translates system actions into+ * [InAppCallRegistry] calls, and reflects call state back so the system surface stays in step.+ *+ * `audioModeIsVoip` is what makes Telecom manage audio mode and focus for us, which is why the app does+ * not request focus itself.+ */+class InAppCallConnection : Connection(), InAppCallConnectionBridge {+    init {+        audioModeIsVoip = true+        connectionCapabilities = connectionCapabilities or CAPABILITY_MUTE+    }++    override fun onAnswer() {+        InAppCallRegistry.answer()+    }++    override fun onReject() {+        InAppCallRegistry.reject()+        setDisconnected(DisconnectCause(DisconnectCause.REJECTED))+        destroy()+    }++    override fun onDisconnect() {+        InAppCallRegistry.hangup()+        setDisconnected(DisconnectCause(DisconnectCause.LOCAL))+        destroy()+    }++    override fun onAbort() {+        InAppCallRegistry.hangup()+        setDisconnected(DisconnectCause(DisconnectCause.CANCELED))+        destroy()+    }++    /** The system mute button, as opposed to the in-app one. */+    override fun onMuteStateChanged(isMuted: Boolean) {+        if (InAppCallRegistry.state.value.muted != isMuted) InAppCallRegistry.toggleMuted()+    }++    override fun onCallActive() {+        setActive()+    }++    override fun onCallEnded() {+        setDisconnected(DisconnectCause(DisconnectCause.REMOTE))+        destroy()+    }+}++/**+ * Self-managed [ConnectionService] for WhatsApp and Signal calls.+ *+ * Both directions are mirrors of a call the line has already begun, so neither creates one: the+ * connection just binds the system surface to [InAppCallRegistry].+ */+class InAppCallConnectionService : ConnectionService() {+    override fun onCreateOutgoingConnection(+        connectionManagerPhoneAccount: PhoneAccountHandle?,+        request: ConnectionRequest?,+    ): Connection {+        val state = InAppCallRegistry.state.value+        val connection = InAppCallConnection().apply {+            setAddress(+                request?.address ?: Uri.fromParts(PhoneAccount.SCHEME_SIP, state.peerId, null),+                TelecomManager.PRESENTATION_ALLOWED,+            )+            setCallerDisplayName(state.peerName, TelecomManager.PRESENTATION_ALLOWED)+            videoState = VideoProfile.STATE_AUDIO_ONLY+            setDialing()+            connectionProperties = connectionProperties or Connection.PROPERTY_SELF_MANAGED+        }+        InAppCallRegistry.connection = connection+        // Already Active by the time Telecom catches up on a fast connect.+        if (state.phase == InAppCallPhase.Active) connection.setActive()+        InAppCallForegroundService.start(applicationContext)+        return connection+    }++    override fun onCreateIncomingConnection(+        connectionManagerPhoneAccount: PhoneAccountHandle?,+        request: ConnectionRequest?,+    ): Connection {+        val state = InAppCallRegistry.state.value+        val address = request?.extras?.getParcelable(TelecomManager.EXTRA_INCOMING_CALL_ADDRESS) as? Uri+        val connection = InAppCallConnection().apply {+            setAddress(+                address ?: Uri.fromParts(PhoneAccount.SCHEME_SIP, state.peerId, null),+                TelecomManager.PRESENTATION_ALLOWED,+            )+            setCallerDisplayName(state.peerName, TelecomManager.PRESENTATION_ALLOWED)+            videoState = VideoProfile.STATE_AUDIO_ONLY+            setInitializing()+            setRinging()+            connectionProperties = connectionProperties or Connection.PROPERTY_SELF_MANAGED+        }+        InAppCallRegistry.connection = connection+        InAppCallForegroundService.start(applicationContext)+        return connection+    }++    override fun onCreateOutgoingConnectionFailed(+        connectionManagerPhoneAccount: PhoneAccountHandle?,+        request: ConnectionRequest?,+    ) {+        InAppCallRegistry.hangup()+    }+}
communicate/src/main/java/com/vayunmathur/communicate/ui/call/InAppCallScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/call/InAppCallScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/call/InAppCallScreen.ktnew file mode 100644index 0000000000..5fbcbef5c2--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/call/InAppCallScreen.kt@@ -0,0 +1,168 @@+package com.vayunmathur.communicate.ui.call++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.CommunicateLine+import com.vayunmathur.communicate.data.call.InAppCallPhase+import com.vayunmathur.communicate.data.call.InAppCallRegistry+import com.vayunmathur.library.ui.FilledIconButton+import com.vayunmathur.library.ui.IconCall+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconMic+import com.vayunmathur.library.ui.IconMicOff+import com.vayunmathur.library.ui.IconVolumeUp+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text+import kotlinx.coroutines.delay++/**+ * Full-screen UI for an in-app WhatsApp or Signal call, driven by [InAppCallRegistry].+ *+ * One screen for both lines: the phases and controls are identical, and only the label differs. Google+ * Voice keeps its own screen because it has DTMF and a different phase model.+ */+@Composable+fun InAppCallScreen(onClose: () -> Unit) {+    val state by InAppCallRegistry.state.collectAsState()++    // A terminal state is shown briefly so the outcome is visible, then dismissed.+    LaunchedEffect(state.phase) {+        if (state.phase == InAppCallPhase.Ended) {+            delay(1500)+            InAppCallRegistry.clearEnded()+            onClose()+        } else if (state.phase == InAppCallPhase.Idle) {+            onClose()+        }+    }++    Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surface) {+        Column(+            modifier = Modifier+                .fillMaxSize()+                .padding(24.dp),+            horizontalAlignment = Alignment.CenterHorizontally,+        ) {+            Spacer(Modifier.height(48.dp))+            Text(+                state.peerName,+                style = MaterialTheme.typography.headlineSmall,+                fontWeight = FontWeight.SemiBold,+            )+            Spacer(Modifier.height(8.dp))+            Text(+                phaseLabel(state.phase, state.line, state.endReason),+                style = MaterialTheme.typography.bodyMedium,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+            if (state.phase == InAppCallPhase.Active && state.connectedAtMs > 0L) {+                Spacer(Modifier.height(4.dp))+                CallDuration(state.connectedAtMs)+            }++            Spacer(Modifier.weight(1f))++            when (state.phase) {+                InAppCallPhase.Incoming -> IncomingControls()+                InAppCallPhase.Ended -> Unit+                else -> InCallControls(muted = state.muted, speaker = state.speaker)+            }+            Spacer(Modifier.height(32.dp))+        }+    }+}++/** Ticks once a second so the readout advances without recomposing the whole screen on every frame. */+@Composable+private fun CallDuration(connectedAtMs: Long) {+    var elapsed by remember(connectedAtMs) { mutableLongStateOf(0L) }+    LaunchedEffect(connectedAtMs) {+        while (true) {+            elapsed = (System.currentTimeMillis() - connectedAtMs).coerceAtLeast(0L) / 1000+            delay(1000)+        }+    }+    val minutes = elapsed / 60+    val seconds = elapsed % 60+    Text(+        "%d:%02d".format(minutes, seconds),+        style = MaterialTheme.typography.bodyMedium,+        color = MaterialTheme.colorScheme.onSurfaceVariant,+    )+}++@Composable+private fun IncomingControls() {+    Row(+        modifier = Modifier.fillMaxWidth(),+        horizontalArrangement = Arrangement.SpaceEvenly,+    ) {+        CallActionButton(onClick = { InAppCallRegistry.reject() }) { IconClose() }+        CallActionButton(onClick = { InAppCallRegistry.answer() }) { IconCall() }+    }+}++@Composable+private fun InCallControls(muted: Boolean, speaker: Boolean) {+    Row(+        modifier = Modifier.fillMaxWidth(),+        horizontalArrangement = Arrangement.SpaceEvenly,+    ) {+        CallActionButton(onClick = { InAppCallRegistry.toggleMuted() }) {+            if (muted) IconMicOff() else IconMic()+        }+        CallActionButton(onClick = { InAppCallRegistry.toggleSpeaker() }) { IconVolumeUp() }+        CallActionButton(onClick = { InAppCallRegistry.hangup() }) { IconClose() }+    }+}++@Composable+private fun CallActionButton(onClick: () -> Unit, icon: @Composable () -> Unit) {+    Box {+        FilledIconButton(onClick = onClick, modifier = Modifier.size(64.dp)) { icon() }+    }+}++@Composable+private fun phaseLabel(phase: InAppCallPhase, line: CommunicateLine?, endReason: String?): String {+    val lineName = when (line) {+        CommunicateLine.Signal -> stringResource(R.string.account_signal)+        CommunicateLine.WhatsApp -> stringResource(R.string.account_whatsapp)+        else -> ""+    }+    return when (phase) {+        InAppCallPhase.Outgoing -> stringResource(R.string.call_state_dialing)+        InAppCallPhase.Incoming -> if (lineName.isBlank()) {+            stringResource(R.string.call_state_incoming_generic)+        } else {+            "${stringResource(R.string.call_state_incoming_generic)} - $lineName"+        }+        InAppCallPhase.Connecting -> stringResource(R.string.call_state_connecting)+        InAppCallPhase.Active -> lineName+        InAppCallPhase.Ended -> endReason?.takeIf { it.isNotBlank() }+            ?: stringResource(R.string.call_state_ended)+        InAppCallPhase.Idle -> ""+    }+}
communicate/src/main/res/values/strings.xml
diff --git a/communicate/src/main/res/values/strings.xml b/communicate/src/main/res/values/strings.xmlindex e115fd0b21..f3eea77bff 100644--- a/communicate/src/main/res/values/strings.xml+++ b/communicate/src/main/res/values/strings.xml@@ -113,4 +113,12 @@     <string name="signal_safety_number_accept">Accept new safety number</string>     <string name="signal_safety_number_accept_failed">Could not accept the new safety number</string>     <string name="call_failed">Could not start the call</string>+    <!-- Shared by the WhatsApp and Signal call UI; call_state_incoming is Google Voice specific. -->+    <string name="call_state_connecting">Connecting…</string>+    <string name="call_state_incoming_generic">Incoming call</string>+    <string name="account_whatsapp">WhatsApp</string>+    <string name="inapp_ongoing_call">Ongoing call</string>+    <string name="inapp_call_channel_name">Calls</string>+    <string name="inapp_incoming_call_channel_name">Incoming calls</string>+    <string name="inapp_incoming_call_channel_desc">Ringing for WhatsApp and Signal calls</string> </resources>