// What a Chat message carries besides its words: photos and videos from the // library, a picture taken with the camera, a file, and a voice message held // to record. Each is copied to a // file of the phone's own and handed to `chat.act send` as an attachment // ({path, mime, name, width, height, kind, durationMs, waveform}); the core // draws its bubble at once from that file and `chat.flush` seals and // uploads it. Nothing here reads a whole file into memory. #if os(iOS) import AVFoundation import CottonKit import CottonComposer import CoreTransferable import ImageIO import PhotosUI import SwiftUI import UniformTypeIdentifiers enum ChatOutbox { /// Where an attachment waits until the core has sealed it. static var folder: URL { let url = FileManager.default.temporaryDirectory.appendingPathComponent("chat-out", isDirectory: true) try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) return url } /// A picked or recorded file as the core takes it. static func attachment(at url: URL, kind: String? = nil, name: String? = nil) -> ChatAttachment { let type = UTType(filenameExtension: url.pathExtension) let mime = type?.preferredMIMEType ?? "application/octet-stream" var attachment = ChatAttachment(path: url.path, mime: mime, name: name ?? url.lastPathComponent) if type?.conforms(to: .image) == true { attachment.kind = kind ?? "photo" if let source = CGImageSourceCreateWithURL(url as CFURL, nil), let props = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any] { attachment.width = (props[kCGImagePropertyPixelWidth] as? NSNumber)?.doubleValue attachment.height = (props[kCGImagePropertyPixelHeight] as? NSNumber)?.doubleValue } attachment.preview = ChatPreviewMaker.make(url) } else if type?.conforms(to: .movie) == true { attachment.kind = kind ?? "video" } else { attachment.kind = kind ?? "file" } return attachment } /// Files picked with Files, as the core takes them: each copied in and named as it was picked (the copy's own /// name carries a prefix that keeps two picks of one name apart; WhatsApp shows a document under its name). static func pickedFiles(_ urls: [URL]) -> [ChatAttachment] { urls.compactMap { url in copyIn(url).map { attachment(at: $0, kind: "file", name: url.lastPathComponent) } } } /// A file from elsewhere, copied in (its security scope held while copying). static func copyIn(_ url: URL) -> URL? { let scoped = url.startAccessingSecurityScopedResource() defer { if scoped { url.stopAccessingSecurityScopedResource() } } let target = folder.appendingPathComponent("\(UUID().uuidString)-\(url.lastPathComponent)") do { try FileManager.default.copyItem(at: url, to: target) } catch { return nil } return target } } /// A photo or a video the library hands over as a file, never as bytes. struct ChatPickedFile: Transferable { let url: URL static var transferRepresentation: some TransferRepresentation { FileRepresentation(importedContentType: .movie) { received in ChatPickedFile(url: try copy(received.file)) } FileRepresentation(importedContentType: .image) { received in ChatPickedFile(url: try copy(received.file)) } } private static func copy(_ file: URL) throws -> URL { let target = ChatOutbox.folder.appendingPathComponent("\(UUID().uuidString).\(file.pathExtension)") try FileManager.default.copyItem(at: file, to: target) return target } } /// What the attachment sheet offers (Android's AttachSheet): the camera, the /// library's photos and videos, a file, or a poll (a WhatsApp chat whose /// outbox takes one, CONTRACT.md "Making a poll"). enum ChatAttachChoice: Equatable { case camera, photos, file, poll } /// The attachment sheet, a Warm panel at the conversation's root: the files where the writing box takes them /// (`attach`), and Poll where the core offers one (`composer.poll`), alone where no file goes. struct ChatAttachSheet: View { var files = true var poll: String? = nil let choose: (ChatAttachChoice) -> Void @Environment(\.chatLook) private var look var body: some View { VStack(alignment: .leading, spacing: 0) { if files { if Camera.isAvailable { WarmRow(symbol: "camera", words: ShellLines.line("chat", "app.compose.camera"), id: "chat-attach-camera") { choose(.camera) } } WarmRow(symbol: "photo.on.rectangle", words: ShellLines.line("chat", "app.attach.photos"), id: "chat-attach-photo") { choose(.photos) } WarmRow(symbol: "doc", words: ShellLines.line("chat", "app.attach.file"), id: "chat-attach-file") { choose(.file) } } if let poll { WarmRow(symbol: "chart.bar.xaxis", words: poll, id: "chat-attach-poll") { choose(.poll) } } } .padding(.horizontal, Warm.side) .padding(.vertical, 14) .accessibilityElement(children: .contain) .accessibilityIdentifier("chat-attach-sheet") } } /// The plus beside the writing box: it opens the attachment sheet, and runs /// what was chosen there (the library, the camera, the files). Pictures and /// videos wait in the writing box for a caption (`stage`); files go at once. struct ChatAttachButton: View { let label: String @Binding var chosen: ChatAttachChoice? let open: () -> Void let stage: ([ChatAttachment]) -> Void let send: ([ChatAttachment]) -> Void @Environment(\.chatLook) private var look @Environment(ToastCenter.self) private var toasts: ToastCenter? @State private var picking = false @State private var shooting = false @State private var importing = false @State private var items: [PhotosPickerItem] = [] var body: some View { Button(action: open) { Image(systemName: "plus") .font(.system(size: 19, weight: .medium)) .foregroundStyle(look.colours.text) .frame(width: 36, height: 36) .background(Circle().fill(look.colours.bar)) .frame(width: 40, height: 40) } .buttonStyle(.plain) .accessibilityLabel(Text(verbatim: label)) .accessibilityIdentifier("chat-attach") .onChange(of: chosen) { _, choice in guard let choice else { return } chosen = nil switch choice { // A poll's sheet stands at the conversation's root, opened there. case .poll: break case .camera: openCamera() case .photos: #if COTTON_DEV // Chat Dev's invented picture, as the library would hand it over (`-chat-warm-pick YES`). if ChatWarmSeed.asked, ChatWarmSeed.pick, let picked = ChatWarmSeed.pickedPhoto() { stage([picked]) return } #endif picking = true case .file: #if COTTON_DEV // Chat Dev's invented document, as Files would hand it over (`-chat-warm-pick-file`). if ChatWarmSeed.asked, ChatWarmSeed.pickFile != nil, let picked = ChatWarmSeed.pickedDocument() { let attachments = ChatOutbox.pickedFiles([picked]) if !attachments.isEmpty { send(attachments) } return } #endif importing = true } } .photosPicker(isPresented: $picking, selection: $items, maxSelectionCount: 10, matching: .any(of: [.images, .videos])) .fullScreenCover(isPresented: $shooting) { CameraPicker(onTaken: { taken in shooting = false // The JPEG the camera wrote, moved where an attachment waits, and // waiting for its caption as a library picture does. let target = ChatOutbox.folder.appendingPathComponent(taken.lastPathComponent) guard (try? FileManager.default.moveItem(at: taken, to: target)) != nil else { return } stage([ChatOutbox.attachment(at: target)]) }, onCancelled: { shooting = false }) } .fileImporter(isPresented: $importing, allowedContentTypes: [.item], allowsMultipleSelection: true) { result in guard case .success(let urls) = result else { return } let attachments = ChatOutbox.pickedFiles(urls) if !attachments.isEmpty { send(attachments) } } .onChange(of: items) { _, picked in guard !picked.isEmpty else { return } items = [] Task { var attachments: [ChatAttachment] = [] for item in picked { if let file = try? await item.loadTransferable(type: ChatPickedFile.self) { attachments.append(ChatOutbox.attachment(at: file.url)) } } if !attachments.isEmpty { stage(attachments) } } } } /// The camera, once the authority has it allowed; its refusal said if not. private func openCamera() { Task { if let refusal = await Camera.refusal(SystemCapabilityAuthority()) { toasts?.show(refusal, tone: .error) } else { shooting = true } } } } /// MAKING A POLL in a WhatsApp chat (CONTRACT.md "Making a poll"; Android's PollSheet): the question, one option a /// line (a new line stands under the last one written, up to the core's `most`), whether more than one may be chosen, /// and Send, live with a question and two options. The core checks what goes (trimmed, the same option once) and says /// what is missing; nothing is decided here. In Comms' own look, in a panel at the conversation's root. struct ChatPollSheet: View { let words: ChatPollMaker let send: (_ question: String, _ options: [String], _ many: Bool) -> Void @Environment(\.chatLook) private var look @Environment(\.closeCard) private var close @Environment(\.dismiss) private var dismiss @State private var question = "" @State private var options = ["", ""] @State private var many = false @FocusState private var focused: Int? private static func written(_ text: String) -> Bool { !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } private var ready: Bool { Self.written(question) && options.filter(Self.written).count >= 2 } var body: some View { VStack(alignment: .leading, spacing: 0) { HStack { WarmRound(symbol: "xmark", label: ShellLines.line("chat", "app.attach.close"), id: "chat-poll-close") { CardClosing.close(close, else: dismiss) } Spacer() WarmPill(words: words.send, id: "chat-poll-send", accent: true) { guard ready else { return } send(question, options.filter(Self.written), many) } .disabled(!ready) .opacity(ready ? 1 : 0.5) } .padding(.horizontal, Warm.side - 6) .padding(.top, 10) ScrollView { VStack(alignment: .leading, spacing: 8) { Text(verbatim: words.label) .font(look.font(28, .bold)).kerning(-0.5).foregroundStyle(look.colours.text) .accessibilityAddTraits(.isHeader) .padding(.bottom, 4) field($question, hint: words.question, id: "chat-poll-question", at: -1, weight: .semibold) ForEach(options.indices, id: \.self) { i in field(option(i), hint: i >= 2 && i == options.count - 1 && options[i].isEmpty ? words.add : words.option, id: "chat-poll-option-\(i)", at: i) } Toggle(isOn: $many) { Text(verbatim: words.many).font(look.font(16)).foregroundStyle(look.colours.text) .fixedSize(horizontal: false, vertical: true) } .tint(look.colours.accent) .frame(minHeight: 52) .padding(.top, 4) .accessibilityIdentifier("chat-poll-many") } .padding(.horizontal, Warm.side) .padding(.vertical, 12) } } .accessibilityElement(children: .contain) .accessibilityIdentifier("chat-poll-sheet") .onAppear { focused = -1 } } /// Option `i`: once the last line has words, a new one stands under it, up to the core's most. private func option(_ i: Int) -> Binding { Binding(get: { options.indices.contains(i) ? options[i] : "" }, set: { typed in guard options.indices.contains(i) else { return } options[i] = typed if i == options.count - 1, Self.written(typed), options.count < words.most { options.append("") } }) } private func field(_ text: Binding, hint: String, id: String, at: Int, weight: UIFont.Weight = .regular) -> some View { TextField(text: text) { Text(verbatim: hint).foregroundStyle(look.colours.faint) } .font(look.font(17, weight)).foregroundStyle(look.colours.text) .focused($focused, equals: at) .submitLabel(.next) .onSubmit { focused = at + 1 < options.count ? at + 1 : nil } .padding(.horizontal, 14) .padding(.vertical, 12) .frame(minHeight: 48) .background(RoundedRectangle(cornerRadius: 16, style: .continuous).fill(look.colours.bar)) .accessibilityLabel(Text(verbatim: hint)) .accessibilityIdentifier(id) } } /// The voice message recorder: AAC to a file of the phone's own (as Android /// records: 44.1 kHz, 64 kb/s, one channel), with the level sampled for the /// bubble's waveform (at most 64 bars, 0…1). The composer's microphone drives /// it: held, it records; let go, `send` has the voice message; slid away, it /// is thrown out. Under half a second is no message (Android's rule). @MainActor @Observable final class ChatVoiceRecorder: ComposerRecorder { private let capabilities: any CapabilityAuthority private(set) var recording = false private(set) var elapsed: TimeInterval = 0 private(set) var level: Double = 0 let holdLabel = ShellLines.line("chat", "app.compose.voice") /// What a recording let go is handed to (the thread sends it at once). @ObservationIgnored var send: (ChatAttachment) -> Void = { _ in } @ObservationIgnored private var recorder: AVAudioRecorder? @ObservationIgnored private var levels: [Double] = [] @ObservationIgnored private var ticker: Task? @ObservationIgnored private var url: URL? @ObservationIgnored private var started = ContinuousClock.now /// The finger is still down: a hold let go while the microphone was being asked for records nothing. @ObservationIgnored private var wanted = false /// The audio session was made active for a recording, and is given back after it. @ObservationIgnored private var opened = false #if COTTON_DEV /// Chat Dev's invented recording (`-chat-warm-voice YES`): the simulator has no microphone. @ObservationIgnored private var invented = false #endif static let shortest: TimeInterval = 0.5 init(capabilities: any CapabilityAuthority = SystemCapabilityAuthority()) { self.capabilities = capabilities } func begin() async { wanted = true await start() } func end(cancelled: Bool) { wanted = false if let attachment = stop(keep: !cancelled) { send(attachment) } } /// The microphone is asked through the authority first; the recorder is /// built only after it answered and the session records. func start() async { guard !recording else { return } #if COTTON_DEV if ChatWarmSeed.asked, ChatWarmSeed.voice { invented = true began(url: nil) return } #endif guard await capabilities.gate([.microphone]).isReady, wanted else { return } let session = AVAudioSession.sharedInstance() try? session.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetoothHFP]) try? session.setActive(true) opened = true let url = ChatOutbox.folder.appendingPathComponent("\(UUID().uuidString).m4a") let settings: [String: Any] = [AVFormatIDKey: kAudioFormatMPEG4AAC, AVSampleRateKey: 44_100, AVNumberOfChannelsKey: 1, AVEncoderBitRateKey: 64_000] guard let recorder = try? AVAudioRecorder(url: url, settings: settings) else { return close() } recorder.isMeteringEnabled = true guard recorder.record(), wanted else { recorder.stop() try? FileManager.default.removeItem(at: url) return close() } self.recorder = recorder began(url: url) } private func began(url: URL?) { self.url = url levels = [] elapsed = 0 started = .now recording = true ticker = Task { [weak self] in while !Task.isCancelled { try? await Task.sleep(for: .milliseconds(50)) guard let self, self.recording else { return } self.level = self.sample() self.levels.append(self.level) let gone = ContinuousClock.now - self.started self.elapsed = Double(gone.components.seconds) + Double(gone.components.attoseconds) / 1e18 } } } /// The session given back when no recording came of it. private func close() { guard opened else { return } opened = false try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) } /// The loudness now: the recorder's meter, or the invented recording's rise and fall. private func sample() -> Double { #if COTTON_DEV if invented { return 0.35 + 0.5 * abs(sin(Double(levels.count) * 0.45)) } #endif guard let recorder else { return 0 } recorder.updateMeters() let db = Double(recorder.averagePower(forChannel: 0)) return max(0, min(1, (db + 50) / 50)) } /// Stops; the voice message as an attachment, or nil when cancelled or too short. func stop(keep: Bool) -> ChatAttachment? { ticker?.cancel() ticker = nil guard recording else { return nil } let gone = ContinuousClock.now - started var duration = Double(gone.components.seconds) + Double(gone.components.attoseconds) / 1e18 recorder?.stop() recorder = nil recording = false level = 0 #if COTTON_DEV if invented { invented = false guard keep, duration >= Self.shortest, let made = ChatWarmSeed.recordedVoice() else { return nil } url = made.url duration = made.seconds } #endif if opened { opened = false try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) } guard let url else { return nil } self.url = nil guard keep, duration >= Self.shortest else { try? FileManager.default.removeItem(at: url) return nil } var attachment = ChatOutbox.attachment(at: url, kind: "voice") attachment.mime = "audio/mp4" attachment.durationMs = (duration * 1000).rounded() attachment.waveform = Self.bars(levels, count: 64) return attachment } static func bars(_ levels: [Double], count: Int) -> [Double] { guard levels.count > count else { return levels } let step = Double(levels.count) / Double(count) return (0..