// The system's call UI on an iPhone: CallKit.//// One `CXProvider` (video, one call group of one call, kept out of the// phone's own Recents because the core writes the history and a call must not// be counted twice) and one `CXCallController`. The core's `system_call_*`// effects arrive as the port's calls; the person's acts on the system screen// (answer, end, mute) come back to the center as its methods. The audio// session is activated by CallKit alone (`didActivate`), never by the app.#if os(iOS)import AVFoundationimportCallKitimportFoundation@MainActorpublicfinalclassCallKitSystem: NSObject, SystemCallPort, RingReporter {privatelet provider: CXProviderprivatelet controller = CXCallController()/// Where the person's acts go: set once the center is made.publicweakvar center: CallCenter?/// The calls CallKit holds, reported or started here.privatevar known: Set<UUID> = []/// Ends this app asked for (`CXEndCallAction` the core said to request),/// so the provider's perform does not hand them back as the person's.privatevar endingHere: Set<UUID> = []/// Outgoing calls whose start CallKit has performed: only then may it be told they connect.privatevar startedHere: Set<UUID> = []/// Calls the core said connected before CallKit performed their start (a group's call can be live in/// a quarter second): told once the start is performed.privatevar connectedEarly: Set<UUID> = []privatevar log: @Sendable (String) -> Void/// `icon`: the telephone's template image (PNG data), shown on the/// system call screen's button back into the app.publicinit(icon: Data?, log: @escaping @Sendable (String) -> Void = { _ in }) {let configuration = CXProviderConfiguration() configuration.supportsVideo = true configuration.maximumCallGroups = 1 configuration.maximumCallsPerCallGroup = 1 configuration.includesCallsInRecents = false configuration.supportedHandleTypes = [.phoneNumber, .generic] configuration.iconTemplateImageData = icon provider = CXProvider(configuration: configuration)self.log = logsuper.init() provider.setDelegate(self, queue: nil) }/// Whether CallKit already holds this call (the push reported it).publicfunc holds(_ uuid: UUID) -> Bool { known.contains(uuid) }// MARK: The push's own report/// Report a ring at once, inside the PushKit handler, before the core has/// said anything: iOS ends an app that does not report a call for EVERY/// VoIP push, a stop push included. A call CallKit already holds is/// reported again all the same: CallKit refuses it as already there,/// which is the report iOS asks for. `completion` runs when CallKit has/// taken (or refused) it.publicfunc reportRing(uuid: UUID, video: Bool, completion: @escaping @Sendable () -> Void) {let fresh = known.insert(uuid).insertedlet update = CXCallUpdate() update.hasVideo = video update.supportsHolding = false update.supportsGrouping = false update.supportsUngrouping = false update.supportsDTMF = false provider.reportNewIncomingCall(with: uuid, update: update) { [weakself, log] error iniflet error { log("callkit: the ring was not taken: \(error)")if fresh { Task { @MainActor inself?.known.remove(uuid) } } } completion() } }// MARK: SystemCallPortpublicfunc startOutgoing(uuid: UUID, handle: String, name: String?, video: Bool) { known.insert(uuid)let action = CXStartCallAction(call: uuid, handle: Self.handle(handle, name: name)) action.isVideo = video action.contactIdentifier = name controller.request(CXTransaction(action: action)) { [log] error iniflet error { log("callkit: start refused: \(error)") } }let update = Self.update(handle: handle, name: name, video: video) provider.reportCall(with: uuid, updated: update) }publicfunc outgoingConnecting(uuid: UUID) { provider.reportOutgoingCall(with: uuid, startedConnectingAt: Date()) }publicfunc outgoingConnected(uuid: UUID) {guard startedHere.contains(uuid) else { connectedEarly.insert(uuid)return } provider.reportOutgoingCall(with: uuid, connectedAt: Date()) }publicfunc reportIncoming(uuid: UUID, title: String, handle: String?, video: Bool) {if !known.contains(uuid) { reportRing(uuid: uuid, video: video) {} }// The push reported it: the core's words (the caller's name, once the// ring's box opened) go on as an update.let update = CXCallUpdate() update.localizedCallerName = titleiflet handle, !handle.isEmpty { update.remoteHandle = CXHandle(type: .phoneNumber, value: handle) } update.hasVideo = video provider.reportCall(with: uuid, updated: update) }publicfunc update(uuid: UUID, handle: String, name: String?, video: Bool) { provider.reportCall(with: uuid, updated: Self.update(handle: handle, name: name, video: video)) }publicfunc ended(uuid: UUID, reason: Int?) {guard known.contains(uuid) else { return }iflet reason, let ended = CXCallEndedReason(rawValue: reason) { known.remove(uuid) provider.reportCall(with: uuid, endedAt: Date(), reason: ended)return } endingHere.insert(uuid) controller.request(CXTransaction(action: CXEndCallAction(call: uuid))) { [weakself] error inguardlet error else { return }Task { @MainActor in// CallKit no longer holds it (already ended): it is over either way.self?.log("callkit: end refused: \(error)")self?.endingHere.remove(uuid)self?.known.remove(uuid)self?.provider.reportCall(with: uuid, endedAt: Date(), reason: .remoteEnded) } } }/// A person's number; a group's call (joined late: the core says no number, chat/CONTRACT.md "Group calls")/// is the group, by its name. nonisolated staticfunc handle(_ handle: String, name: String?) -> CXHandle { handle.isEmpty ? CXHandle(type: .generic, value: name ?? handle) : CXHandle(type: .phoneNumber, value: handle) }privatestaticfunc update(handle: String, name: String?, video: Bool) -> CXCallUpdate {let update = CXCallUpdate() update.remoteHandle = Self.handle(handle, name: name) update.localizedCallerName = name update.hasVideo = video update.supportsHolding = false update.supportsGrouping = false update.supportsUngrouping = false update.supportsDTMF = falsereturn update }}// The delegate's queue is the main queue (`setDelegate(_, queue: nil)`), so// each callback is on the main actor already and is performed there at once.extensionCallKitSystem: CXProviderDelegate { nonisolated publicfunc providerDidReset(_ provider: CXProvider) {MainActor.assumeIsolated {// A reset drops the calls CallKit holds, and only those end. The call daemon (callservicesd) also quits// when it holds none: on a simulator, whose calls CallKit never holds (`SimulatorCallSystem`), its idle// exit reset this provider and hung up a group call twice on CALLS WALK 1 (callservicesd exited// JETSAM_REASON_MEMORY_IDLE_EXIT at 18:17:21.198 and 18:31:17.640; the calls ended cancelled and hung_up// 0.1 to 1 s later, nobody tapping).let held = !known.isEmpty log(held ? "callkit: the provider was reset; the call it held ends" : "callkit: the provider was reset; it held no call") known.removeAll() endingHere.removeAll() startedHere.removeAll() connectedEarly.removeAll()if held { center?.end() } } } nonisolated publicfunc provider(_ provider: CXProvider, perform action: CXStartCallAction) {// The core placed the call already; CallKit is told it is under way, and connected if it is already.let uuid = action.callUUID provider.reportOutgoingCall(with: uuid, startedConnectingAt: nil) action.fulfill()MainActor.assumeIsolated { startedHere.insert(uuid)if connectedEarly.remove(uuid) != nil { self.provider.reportOutgoingCall(with: uuid, connectedAt: Date()) } } } nonisolated publicfunc provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {MainActor.assumeIsolated { center?.answer() } action.fulfill() } nonisolated publicfunc provider(_ provider: CXProvider, perform action: CXEndCallAction) {let uuid = action.callUUIDMainActor.assumeIsolated { known.remove(uuid) startedHere.remove(uuid) connectedEarly.remove(uuid)if endingHere.remove(uuid) == nil {// The person ended it on the system's screen. log("callkit: ended on the system's screen") center?.systemEnded() } } action.fulfill() } nonisolated publicfunc provider(_ provider: CXProvider, perform action: CXSetMutedCallAction) {let muted = action.isMutedMainActor.assumeIsolated {iflet center, center.call.sendingAudio == muted { center.mute(audio: !muted) } } action.fulfill() } nonisolated publicfunc provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) { action.fail() } nonisolated publicfunc provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) {MainActor.assumeIsolated { center?.audioActivated() } } nonisolated publicfunc provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {MainActor.assumeIsolated { center?.audioDeactivated() } }}#endif