Cotton code
189 lines · 7.8 KB · SwiftRaw
// Calls inside Cotton Chat: Calling's engine (the call center, CallKit,// PushKit, WebRTC) handed to Chat's screens as `ChatCalling`. Chat places a// call with `chat.call` (answered as `calls.start` is, its effects performed// by the same center) and draws `chat.callScreen` in a window of its own// above everything, the thread's cover included, so a call placed from a// thread stands over it. The VoIP token is filed under this app's bundle id// (`com.cottondb.messages` / `.dev`) by the same registry Calling uses.#if os(iOS)import CottonKitimport CottonUIimport SwiftUIimport UIKit/// The engine as Chat's screens use it.@MainActor@Observablefinal class ChatCallsPort: ChatCalling {    private let engine: CallingEngine    /// The microphone and camera are asked through the one authority.    private let capabilities: any CapabilityAuthority    /// A video call shrinks to picture in picture when the person leaves the app.    private let pip = CallPictureInPicture()    public init(engine: CallingEngine = .shared, capabilities: any CapabilityAuthority = SystemCapabilityAuthority()) {        self.engine = engine        self.capabilities = capabilities    }    private var center: CallCenter { engine.center }    public var stamp: String {        let call = center.call        return [call.phase.rawValue, call.uuid, call.room ?? "", String(call.sendingAudio), String(call.sendingVideo),                String(call.liveAt?.timeIntervalSince1970 ?? 0), String(call.endedAt?.timeIntervalSince1970 ?? 0),                call.reason ?? "", String(center.speaker), String(center.rosterMoved)].joined(separator: "|")    }    public var speaker: Bool { center.speaker }    /// `chat.flush`, filled by Comms (which holds the chat key).    @ObservationIgnored public var flush: (@Sendable () async -> Void)?    public func place(thread: String?, call: String?, video: Bool?, refused: @escaping @MainActor (String) -> Void) {        var request: [String: JSONValue] = [:]        if let thread { request["thread"] = .string(thread) }        if let call { request["call"] = .string(call) }        if let video { request["video"] = .bool(video) }        let center = center        // The microphone (and the camera for video) is asked before a call,        // as Calling does; a call back takes the call's own kind, so the        // camera is asked when the core says the call is video.        let capabilities = capabilities        Task { @MainActor in            let gate = await capabilities.gate([.microphone])            guard gate.isReady else { center.write("calls: call held by \(gate)"); return }            if video == true { _ = await capabilities.ask(.camera) }            center.place("chat.call", .object(request), refused: refused, answered: self.flushing)        }    }    public func join(thread: String, video: Bool, refused: @escaping @MainActor (String) -> Void) {        let center = center        let capabilities = capabilities        center.write("calls: join tapped (video \(video))")        Task { @MainActor in            let gate = await capabilities.gate([.microphone])            guard gate.isReady else { center.write("calls: join held by \(gate)"); return }            if video { _ = await capabilities.ask(.camera) }            center.place("chat.call", .object(["thread": .string(thread), "join": .bool(true)]), refused: refused, answered: self.flushing)        }    }    /// `flush: true` on `chat.call`'s answer: the group's `call` word goes out, off the main thread as after a send.    private func flushing(_ answer: JSONValue) {        guard answer["flush"]?.bool == true, let flush else { return }        Task.detached(priority: .utility) { await flush() }    }    public func read(_ method: String, _ request: JSONValue) async -> JSONValue? {        await center.read(method, request)    }    public func answer() { center.answer() }    public func decline() { center.decline() }    public func end() { ChatCallLog.write("call: End tapped"); center.end() }    public func toggleMute() { center.toggleMute() }    public func toggleVideo() {        Task { @MainActor in            if !center.call.sendingVideo { guard await capabilities.ask(.camera) == .authorized else { return } }            center.toggleVideo()        }    }    public func toggleSpeaker() { center.toggleSpeaker() }    public func flipCamera() { engine.peer.flipCamera() }    public func remoteVideo() -> AnyView { AnyView(ChatCallVideo(video: engine.peer.video, remote: true, pip: pip)) }    public func localVideo() -> AnyView { AnyView(ChatCallVideo(video: engine.peer.video, remote: false, pip: nil)) }    public func memberVideo(_ member: String) -> AnyView { AnyView(ChatCallMemberVideo(video: engine.peer.video, member: member)) }}/// One side's picture, redrawn as the track comes and goes.private struct ChatCallVideo: View {    let video: CallVideo    let remote: Bool    /// Where the other person's video goes when the app is left.    let pip: CallPictureInPicture?    var body: some View {        if remote {            CallVideoView(track: video.remote)                .background {                    if let pip { CallPictureInPictureSource(pip: pip, track: video.remote) }                }        } else {            CallVideoView(track: video.local, mirrored: true)        }    }}/// One person's video on a group call, redrawn as their track comes and goes.private struct ChatCallMemberVideo: View {    let video: CallVideo    let member: String    var body: some View {        CallVideoView(track: video.remotes[member])    }}/// A window over the app's own that takes touches only where the call draws (`ChatCallTouch`).private final class ChatCallWindow: UIWindow {    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {        guard let frame = ChatCallTouch.frame, frame.contains(point) else { return nil }        return super.hitTest(point, with: event)    }}@MainActorprivate enum ChatCallWindows {    static var window: UIWindow?    static func install(_ port: ChatCallsPort) {        guard window == nil else { return }        guard let scene = UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene })                .first(where: { $0.activationState != .unattached }) else {            ChatCallLog.write("call window: no scene to draw in")            return        }        ChatCallLog.write("call window: installed")        let window = ChatCallWindow(windowScene: scene)        let host = UIHostingController(rootView: ChatCallOverlay(calls: port))        host.view.backgroundColor = .clear        window.rootViewController = host        window.windowLevel = .alert - 1        window.backgroundColor = .clear        window.isHidden = false        self.window = window    }}public struct ChatCallsShell: ViewModifier {    @State private var port = ChatCallsPort()    public init() {}    public func body(content: Content) -> some View {        content            // The folded call bar's room at the top (`ChatCallFold`).            .chatCallRoom()            .environment(\.chatCalls, port)            .onAppear {                // Comms draws Take notes' mark: the room is told so on every call (chat/CONTRACT.md "Take notes").                CallingEngine.shared.center.can = ["notes"]                ChatCallWindows.install(port)                // A missed call's Call back, from its notification (`chat.call { call }`).                let port = port                ChatNotificationHooks.callBack = { call in port.place(thread: nil, call: call, video: nil, refused: { _ in }) }            }            .task { CallingEngine.shared.center.refresh() }    }}extension View {    /// Calls inside Cotton Chat round this view: Calling's engine, Chat's screens.    public func chatCallsShell() -> some View { modifier(ChatCallsShell()) }}#endif