Cotton code
423 lines · 17.3 KB · SwiftRaw
// THE SAFETY NUMBER (CONTRACT.md "Safety number", SEALING.md "Safety// numbers"): what two people compare to know their chat is sealed for each// other's phones and nobody else's. Opened from the person's page (its Safety// number row) and from the chat's quiet "safety number changed" line. The// code is drawn as a QR, large, centred; under it the twelve groups in three// rows of four; the core's words; Scan their code (the camera reads QR codes// only, the first one read goes to `chat.safety.scan` and the camera closes);// Mark as verified / Clear verified (`chat.safety.verify`). Every word is the// core's or the kit's; the number and the code are the core's, drawn as they// come. Nothing is sent to anyone, and the camera's picture is never kept.//// `chat.safety` and `chat.safety.scan` seal, so they go with this phone's chat// key through the chat engine (`CottonChatting.keyed`). In Comms Dev,// `-chat-safety-scan <payload>` hands that payload to Scan their code in place// of the camera (the simulator has none); with `-chat-warm-seed`, `theirs`,// `old` and `other` name the invented codes (ChatWarmSeed).#if os(iOS)import CoreImageimport CoreImage.CIFilterBuiltinsimport CottonKitimport SwiftUIimport UIKit/// `chat.safety` (CONTRACT.md "Safety number").struct ChatSafetyAnswer: Codable, Equatable, Sendable {    struct Words: Codable, Equatable, Sendable {        var title: String        var line: String        var changes: String        var scan: String        var verify: String        var unverify: String        var verified: String        var checkAgain: String?    }    var thread: String    var name: String    /// Twelve groups of five digits.    var number: [String]    /// The QR's text.    var code: String    var verified: Bool    var changedAt: String?    var wasVerified: Bool?    var words: Words}/// `chat.safety.scan`.struct ChatSafetyScanAnswer: Codable, Equatable, Sendable {    /// `matched`, `notMatched` or `notThisChat`.    var result: String    var verified: Bool    var said: String}enum ChatSafetyMethod {    static let show = "chat.safety"    static let scan = "chat.safety.scan"    static let verify = "chat.safety.verify"}/// What the screen asks: through the chat engine, which holds this phone's chat key.@MainActorstruct ChatSafetyAsk {    let chat: (any CottonChatting)?    let core: (any CottonCalling)?    func callAsFunction<T: Decodable>(_ method: String, _ request: [String: JSONValue], as _: T.Type) async throws -> T {        #if COTTON_DEV        // Comms Dev's invented people answer from the seed, in front of the core.        if ChatWarmSeed.asked, let core {            return try await core.call(method, request, as: T.self)        }        #endif        guard let chat else { throw CottonCallError(code: "not_signed_in", message: ShellLines.line("chat", "refused.not_signed_in")) }        let answer = try await chat.keyed(method, request)        return try JSONDecoder().decode(T.self, from: JSONEncoder().encode(answer))    }}/// What a scan said, under the camera's button.private struct ChatSafetySaid: Equatable {    var words: String    var matched: Bool    /// Scan again is offered (not matched, another chat's code, a refusal).    var again: Bool}struct ChatSafetyScreen: View {    let thread: String    let close: () -> Void    @Environment(\.chatLook) private var look    @Environment(\.cottonChat) private var chat    @Environment(\.cottonCore) private var core    @Environment(\.openURL) private var openURL    @Environment(\.dynamicTypeSize) private var typeSize    @Environment(\.cottonCapabilities) private var capabilities    @Environment(ToastCenter.self) private var toasts: ToastCenter?    @State private var answer: ChatSafetyAnswer?    @State private var refused: String?    @State private var said: ChatSafetySaid?    @State private var scanning = false    /// The camera refused, in the shared words, and whether Settings would turn it on.    @State private var noCamera: (said: String, settings: Bool)?    @State private var busy = false    private var ask: ChatSafetyAsk { ChatSafetyAsk(chat: chat, core: core) }    var body: some View {        ScrollView {            VStack(alignment: .leading, spacing: 0) {                HStack {                    WarmRound(symbol: "chevron.left", label: ShellLines.line("words", "back"), id: "chat-safety-back", tap: close)                    Spacer()                }                .padding(.horizontal, Warm.side - 6)                Text(verbatim: answer?.words.title ?? ChatWords.line("safety.title"))                    .font(look.font(26, .bold))                    .kerning(-0.3)                    .foregroundStyle(look.colours.text)                    .accessibilityAddTraits(.isHeader)                    .padding(.horizontal, Warm.side)                    .padding(.top, 8)                if let answer {                    shown(answer)                } else if let refused {                    Text(verbatim: refused)                        .font(look.font(16)).foregroundStyle(look.colours.dim)                        .fixedSize(horizontal: false, vertical: true)                        .padding(.horizontal, Warm.side)                        .padding(.top, 18)                        .accessibilityIdentifier("chat-safety-refused")                } else {                    ProgressView().frame(maxWidth: .infinity).padding(.top, 60)                }            }            .padding(.bottom, 40)        }        .scrollIndicators(.hidden)        .background(look.colours.ground.ignoresSafeArea())        .accessibilityIdentifier("chat-safety-page")        .task { await read() }        .fullScreenCover(isPresented: $scanning) {            ChatSafetyCamera(title: answer?.words.scan ?? ChatWords.line("safety.scan")) { code in                scanning = false                if let code { Task { await scanned(code) } }            } refused: {                scanning = false                noCamera = (CapabilityRefusal.sentence(.camera, .unavailable) ?? "", false)            }            .environment(\.chatLook, look)        }    }    @ViewBuilder private func shown(_ answer: ChatSafetyAnswer) -> some View {        VStack(alignment: .leading, spacing: 0) {            if answer.verified {                HStack(spacing: 6) {                    Image(systemName: "checkmark.seal.fill").accessibilityHidden(true)                    Text(verbatim: answer.words.verified).font(look.font(15, .semibold))                }                .foregroundStyle(look.colours.accent)                .frame(maxWidth: .infinity)                .padding(.top, 16)                .accessibilityElement(children: .combine)                .accessibilityIdentifier("chat-safety-verified")            }            ChatSafetyCode(code: answer.code, label: ChatWords.line("safety.code", ["name": answer.name]))                .frame(maxWidth: .infinity)                .padding(.top, 18)            groups(answer.number)                .frame(maxWidth: .infinity)                .padding(.top, 20)            VStack(alignment: .leading, spacing: 10) {                if let again = answer.words.checkAgain {                    Text(verbatim: again)                        .font(look.font(15, .semibold)).foregroundStyle(look.colours.text)                        .fixedSize(horizontal: false, vertical: true)                        .accessibilityIdentifier("chat-safety-check-again")                }                Text(verbatim: answer.words.line)                    .font(look.font(15)).foregroundStyle(look.colours.text)                    .fixedSize(horizontal: false, vertical: true)                Text(verbatim: answer.words.changes)                    .font(look.font(14)).foregroundStyle(look.colours.dim)                    .fixedSize(horizontal: false, vertical: true)            }            .padding(.horizontal, Warm.side)            .padding(.top, 22)            if let said { saidLine(said) }            if let noCamera { cameraRefused(noCamera) }            acts(answer)        }    }    /// The twelve groups in three rows of four, tabular figures; two to a row where four would not fit.    private func groups(_ number: [String]) -> some View {        let indexed = Array(number.enumerated())        func grid(_ perRow: Int) -> some View {            Grid(horizontalSpacing: 18, verticalSpacing: 10) {                ForEach(Array(stride(from: 0, to: indexed.count, by: perRow)), id: \.self) { start in                    GridRow {                        ForEach(indexed[start..<min(start + perRow, indexed.count)], id: \.offset) { pair in                            Text(verbatim: pair.element)                                .font(look.font(20, .medium).monospacedDigit())                                .foregroundStyle(look.colours.text)                                .lineLimit(1)                                .fixedSize()                                .accessibilityIdentifier("chat-safety-group-\(pair.offset)")                        }                    }                }            }            .padding(.horizontal, Warm.side)        }        return ViewThatFits(in: .horizontal) {            grid(typeSize.isAccessibilitySize ? 2 : 4)            grid(2)            grid(1)        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("chat-safety-number")    }    private func saidLine(_ said: ChatSafetySaid) -> some View {        HStack(alignment: .firstTextBaseline, spacing: 8) {            if said.matched {                Image(systemName: "checkmark.circle.fill").foregroundStyle(look.colours.accent).accessibilityHidden(true)            }            Text(verbatim: said.words)                .font(look.font(15, .semibold))                .foregroundStyle(said.matched ? look.colours.text : look.colours.danger)                .fixedSize(horizontal: false, vertical: true)        }        .padding(14)        .frame(maxWidth: .infinity, alignment: .leading)        .background(RoundedRectangle(cornerRadius: 16, style: .continuous).fill(look.colours.bar))        .padding(.horizontal, Warm.side)        .padding(.top, 18)        .accessibilityElement(children: .combine)        .accessibilityIdentifier("chat-safety-said")    }    /// The camera was refused: said, and Settings where a switch there turns it back on.    private func cameraRefused(_ refusal: (said: String, settings: Bool)) -> some View {        VStack(alignment: .leading, spacing: 8) {            Text(verbatim: refusal.said)                .font(look.font(15)).foregroundStyle(look.colours.text)                .fixedSize(horizontal: false, vertical: true)            if refusal.settings {                WarmPill(words: ChatWords.line("find.settings"), id: "chat-safety-settings") {                    if let url = CapabilityRefusal.settingsURL { openURL(url) }                }            }        }        .padding(14)        .frame(maxWidth: .infinity, alignment: .leading)        .background(RoundedRectangle(cornerRadius: 16, style: .continuous).fill(look.colours.bar))        .padding(.horizontal, Warm.side)        .padding(.top, 18)        .accessibilityIdentifier("chat-safety-no-camera")    }    /// Scan their code (or Scan again), then Mark as verified / Clear verified.    private func acts(_ answer: ChatSafetyAnswer) -> some View {        VStack(alignment: .leading, spacing: 10) {            WarmPill(words: said?.again == true ? ChatWords.line("safety.scan_again") : answer.words.scan, id: "chat-safety-scan", accent: true) { scan() }            WarmPill(words: answer.verified ? answer.words.unverify : answer.words.verify, id: "chat-safety-verify") {                Task { await verify(!answer.verified) }            }        }        .disabled(busy)        .padding(.horizontal, Warm.side)        .padding(.top, 22)    }    // MARK: asks    private func read() async {        do {            answer = try await ask(ChatSafetyMethod.show, ["thread": .string(thread)], as: ChatSafetyAnswer.self)            refused = nil        } catch {            refused = ActionRefused.words(for: error)        }    }    /// The camera, asked for only now (through the one gate); in Comms Dev, the payload handed in place of it.    private func scan() {        #if COTTON_DEV        if let fed = ChatSafetyFed.payload {            Task { await scanned(fed) }            return        }        #endif        noCamera = nil        Task {            switch await capabilities.gate([.camera]) {            case .ready: scanning = true            case .blocked(let capability, let access):                noCamera = (CapabilityRefusal.sentence(capability, access) ?? "", CapabilityRefusal.offersSettings(access))            }        }    }    private func scanned(_ code: String) async {        busy = true        defer { busy = false }        do {            let result = try await ask(ChatSafetyMethod.scan, ["thread": .string(thread), "code": .string(code)], as: ChatSafetyScanAnswer.self)            said = ChatSafetySaid(words: result.said, matched: result.result == "matched", again: result.result != "matched")        } catch {            said = ChatSafetySaid(words: ActionRefused.words(for: error), matched: false, again: true)        }        await read()    }    private func verify(_ on: Bool) async {        busy = true        defer { busy = false }        do {            _ = try await ask(ChatSafetyMethod.verify, ["thread": .string(thread), "verified": .bool(on)], as: JSONValue.self)            said = nil        } catch {            toasts?.show(ActionRefused.words(for: error), tone: .error)        }        await read()    }}#if COTTON_DEV/// `-chat-safety-scan <payload>`: what Scan their code reads, in place of the camera (the simulator has none).enum ChatSafetyFed {    static var payload: String? {        guard let fed = UserDefaults.standard.string(forKey: "chat-safety-scan"), !fed.isEmpty else { return nil }        return ChatWarmSeed.asked ? ChatWarmSafety.code(named: fed) ?? fed : fed    }}#endif/// The code as a QR (CoreImage's generator), dark on the day look's paper so every camera reads it, in either look.struct ChatSafetyCode: View {    let code: String    let label: String    @Environment(\.chatLook) private var look    var body: some View {        Group {            if let image = Self.image(code) {                Image(decorative: image, scale: 1)                    .interpolation(.none)                    .resizable()                    .scaledToFit()            } else {                Color.clear            }        }        .frame(width: 220, height: 220)        .padding(16)        .background(RoundedRectangle(cornerRadius: 22, style: .continuous).fill(ChatLook.warm(dark: false).colours.ground))        .accessibilityElement()        .accessibilityAddTraits(.isImage)        .accessibilityLabel(Text(verbatim: label))        .accessibilityIdentifier("chat-safety-code")    }    static func image(_ text: String) -> CGImage? {        let filter = CIFilter.qrCodeGenerator()        filter.message = Data(text.utf8)        filter.correctionLevel = "M"        // Dark modules, and clear between them: the tile's paper shows through.        let inked = CIFilter.falseColor()        inked.inputImage = filter.outputImage        inked.color0 = CIColor(cgColor: UIColor(ChatLook.warm(dark: false).colours.text).cgColor)        inked.color1 = CIColor.clear        guard let output = inked.outputImage?.transformed(by: CGAffineTransform(scaleX: 10, y: 10)) else { return nil }        return CIContext().createCGImage(output, from: output.extent)    }}/// The camera, reading QR codes only: the first one read is handed back and the camera closes. Its picture is never kept.private struct ChatSafetyCamera: View {    let title: String    let read: (String?) -> Void    let refused: () -> Void    @Environment(\.chatLook) private var look    var body: some View {        ZStack(alignment: .top) {            Color.black.ignoresSafeArea()            ChatQRReader(read: { read($0) }, refused: refused).ignoresSafeArea()            HStack(spacing: 12) {                WarmRound(symbol: "xmark", label: ShellLines.line("words", "close"), id: "chat-safety-camera-close") { read(nil) }                Text(verbatim: title)                    .font(look.font(17, .semibold))                    .foregroundStyle(ChatLook.warm(dark: true).colours.text)                    .accessibilityAddTraits(.isHeader)                Spacer(minLength: 0)            }            .padding(.horizontal, Warm.side - 6)            .padding(.top, 8)        }        .accessibilityIdentifier("chat-safety-camera")    }}/// The back camera's QR reader, as the app builds it (`App/Cotton/Camera+AVFoundation.swift`, `CameraCaptures`); an app/// built without a camera says it cannot open, as a refusal.private struct ChatQRReader: UIViewControllerRepresentable {    let read: (String) -> Void    let refused: () -> Void    func makeUIViewController(context: Context) -> UIViewController {        if let reader = CameraCaptures.qrReader(read: read, refused: refused) { return reader }        DispatchQueue.main.async { refused() }        return UIViewController()    }    func updateUIViewController(_ controller: UIViewController, context: Context) {}}#endif