// What Cotton Chat's screens ask of the core: `chat.list`, `chat.thread`,// `chat.compose`, `chat.act` (chat-new-core, on main since 5d2753a3f) and// `chat.picture`, `chat.themes` and Settings' `chat.theme`, `chat.text`// and `chat.ground`; what `chat.act` queues is sent by the chat engine,// which holds this phone's chat key.#if os(iOS)importCottonKitimportFoundationimportObservationimport UIKitprotocolChatBook: Sendable {func list(_ ask: ChatListAsk) asyncthrows -> ChatListAnswerfunc thread(_ ask: ChatThreadAsk) asyncthrows -> ChatThreadAnswerfunc compose(_ ask: ChatComposeAsk) asyncthrows -> ChatComposeAnswerfunc act(_ ask: ChatActAsk) asyncthrows -> ChatActAnswer/// Accept, block or refuse a stranger's request (`chat.accept` …).func decide(_ thread: String, _ method: String) asyncthrowsfunc themes() asyncthrows -> ChatThemesAnswerfunc choose(theme: String, dark: Bool) asyncthrows -> ChatThemesAnswerfunc setText(_ id: String) asyncthrows -> ChatThemesAnswerfunc setGround(_ ground: String) asyncthrows -> ChatThemesAnswer/// The Calls tile, newest first, 80 a page (`chat.calls {after?}`).func calls(after: String?) asyncthrows -> ChatCallsAnswer/// Sends what an act queued, off the main thread (`ActAnswer.flush`).func flush() async/// A message's attachment by `message` and `index`, as a file on the/// phone; or a photo by its key where `photosByKey` is false.func picture(media: String?, message: String?, index: Int?) async -> URL?/// Any attachment of a message as a file on the phone, under its own/// extension (`chat.file`). Refused `file_gone` or `file_offline` in the/// kit's words, which are said as they are.func file(message: String, index: Int) asyncthrows -> ChatFileAnswer/// Whether a person's photo key is drawn by Cotton's own picture store/// (`RecordPicture`) rather than through `picture(media:)`.var photosByKey: Bool { get }/// Changes that came in, each naming the one row or bubble it touches.func changes() -> AsyncStream<ChatChange>/// A message's picture asked once (`chat.picture`): its file, gone in the core's word, or not yet.func findPicture(message: String, index: Int) async -> ChatPictureFound// Pictures at once (ChatPicturesAhead.swift).func ahead(thread: String, messages: [String]) asyncfunc warm(constrained: Bool) async -> Intfunc previewsWanted() async -> [ChatPreviewWanted]func setPreviews(_ made: [ChatPreviewMade]) async// The voice player (ChatVoice.swift).func voiceSpeed() async -> Doublefunc setVoiceSpeed(_ speed: Double) asyncfunc waveformsWanted() async -> [ChatPreviewWanted]func setWaveforms(_ made: [ChatWaveformMade]) async// Link previews (ChatLinkFetch.swift, CONTRACT.md "Link previews")./// The page this phone fetched from `url`, read by the core as its card (`chat.linkCard`); nil when none goes.func linkCard(thread: String, url: String, page: String) async -> ChatLinkCardAnswer?}extensionChatBook {/// The open chat shows these messages (`chat.ahead`): their pictures, and those on each side, come onto the phone.func ahead(thread: String, messages: [String]) async {}/// The chat list's warm (`chat.warm`): answers how many pictures it fetched, 0 when there was nothing left.func warm(constrained: Bool) async -> Int { 0 }/// Pictures on this phone with no preview yet (`chat.previews`).func previewsWanted() async -> [ChatPreviewWanted] { [] }/// Previews made here, written into their messages (`chat.preview`).func setPreviews(_ made: [ChatPreviewMade]) async {}/// One speed for every voice message, the person's (`chat.settings` voiceSpeed): 1 until chosen.func voiceSpeed() async -> Double { 1 }func setVoiceSpeed(_ speed: Double) async {}func linkCard(thread: String, url: String, page: String) async -> ChatLinkCardAnswer? { nil }/// Voice messages on this phone with no waveform yet (`chat.waveforms`).func waveformsWanted() async -> [ChatPreviewWanted] { [] }/// Waveforms read here, written into their messages (`chat.waveform`).func setWaveforms(_ made: [ChatWaveformMade]) async {}/// A book that says only file or nothing: nothing is "not yet", never gone; gone is the core's word.func findPicture(message: String, index: Int) async -> ChatPictureFound {iflet url = await picture(media: nil, message: message, index: index) { return .file(url) }return .notYet }}/// What one ask for a message's picture found.enumChatPictureFound: Equatable, Sendable {case file(URL)/// The core said so: the store does not hold it and the message is past its first minutes/// (`not_found`), or its bytes did not open (`unreadable`).case gone/// On its way (`not_yet`: still going up, or new and not landed yet), or no answer (no connection):/// asked again soon, never drawn as gone.case notYetstaticfunc of(code: String) -> ChatPictureFound { ["not_found", "unreadable"].contains(code) ? .gone : .notYet }var url: URL? {ifcase .file(let url) = self { return url }returnnil }}/// One thing that changed: a list row, or a thread's bubbles.enumChatChange: Sendable, Equatable {case row(ChatListRow)case bubble(thread: String, ChatBubble)/// Messages arrived below what a thread holds: its newest page is stale.case arrived(thread: String)/// A chat was read on another of the person's phones (`chat.incoming`'s `read`).case read(thread: String)}enumChatBooks { @MainActor staticvar shared: (any ChatBook)?/// The fan the core last answered with a list (`chat.list`'s `fan`). @MainActor staticvar fanTiles: [ChatFanTile] = [] @MainActor staticfunc make(core: (any CottonCalling)?, chat: (any CottonChatting)? = nil) -> any ChatBook {iflet shared { return shared } #if COTTON_DEVifChatWarmSeed.asked, let seeded = ChatWarmSeedBook(long: ChatWarmSeed.long) { shared = seededreturn seeded } #endifguardlet core else { returnCoreChatBook(core: UnreachableCore(), chat: nil) }let book = CoreChatBook(core: core, chat: chat) shared = bookreturn book }/// Whether this app is Cotton Chat (the Messages flavour or its Dev twin).staticvar isChat: Bool { FlavourManifest.current?.flavour.hasPrefix("messages") == true }/// Reads the core's fan once before the board's fan is dealt, so Chat's/// cards stand from the first draw. @MainActor staticfunc prime(core: (any CottonCalling)?) async {guard isChat, fanTiles.isEmpty, let core else { return }iflet answer = try? await core.call(ChatMethod.list, ChatListAsk(filter: "all"), as: ChatListAnswer.self) { fanTiles = answer.fan } }/// The board's cards from the core's fan, in its order: a card per/// filter and source, then Account as the tile's aside.staticfunc cards(_ fan: [ChatFanTile]) -> [ToolView] { fan.compactMap { tile invar card: [String: Any] = ["id": "chat:\(tile.id)", "label": tile.label, "default": tile.id == "all","read": ["table": "thread", "where": [String: String]()]]if tile.id == "account" { card["id"] = "account" card["aside"] = true } else { card["chat"] = tile.id }iflet count = tile.count { card["count"] = count }guardlet data = try? JSONSerialization.data(withJSONObject: card) else { returnnil }returntry? JSONDecoder().decode(ToolView.self, from: data) } }/// The fan as the core answered it, with Chat's own cards on the tile/// whose face was the old stream of chats: All, People, Groups, Unread,/// Archived, a card per source, then Account, in `chat.list`'s order./// Until the core's `shell.fan` deals these itself, they are dealt here/// from the core's own `chat.list` fan. @MainActor staticfunc fan(_ answer: FanAnswer) -> FanAnswer {guard isChat, let stream = answer.stream else { return answer }let cards = cards(fanTiles)guard !cards.isEmpty else { return answer }var answer = answer answer.stream = nilfor index in answer.tiles.indices where answer.tiles[index].key == stream.tool || answer.tiles[index].tool == stream.tool { answer.tiles[index].views = cards answer.tiles[index].ringed = true answer.tiles[index].poster = false answer.tiles[index].viewsTable = stream.tableiflet current = answer.tiles[index].current, cards.contains(where: { $0.id == current }) { continue } answer.tiles[index].current = cards.first?.id }return answer }}/// A core that is not there: every ask is refused, never answered from/// made-up data.structUnreachableCore: CottonCalling {structUnreachable: Error {}func callRaw(_ method: String, requestJSON: String) asyncthrows -> String { throwUnreachable() }func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {}func close() async {}}/// The core's own answers.structCoreChatBook: ChatBook, @unchecked Sendable {let core: any CottonCalling/// The chat engine: it holds the chat key `chat.flush` needs.weakvar chat: (any CottonChatting)?init(core: any CottonCalling, chat: (any CottonChatting)?) {self.core = coreself.chat = chat }privatestructThread: Encodable { let thread: String }privatestructTheme: Encodable { let theme: String; let dark: Bool }privatestructValue: Encodable { let value: String }privatestructGround: Encodable { let ground: String }privatestructAfter: Encodable { let after: String? }privatestructPicture: Encodable { let message: String; let index: Int; let dir: String }privatestructPath: Decodable { let path: String }privatestructOpened: Decodable { let path: String; let previewWanted: Bool? }privatestructAhead: Encodable { let thread: String; let messages: [String] }privatestructWarm: Encodable { let constrained: Bool }privatestructWarmed: Decodable { let fetched: Int? }privatestructWanted: Decodable { let items: [ChatPreviewWanted] }privatestructMade: Encodable { let items: [ChatPreviewMade] }privatestructAnything: Decodable {}privatestructVoiceSettings: Decodable { let voiceSpeed: Double? }privatestructVoiceSpeed: Encodable { let voiceSpeed: Double }privatestructWaves: Encodable { let items: [ChatWaveformMade] }privatestructLinkPage: Encodable { let thread: String; let url: String; let page: String }var photosByKey: Bool { true }func list(_ ask: ChatListAsk) asyncthrows -> ChatListAnswer {let answer = tryawait core.call(ChatMethod.list, ask, as: ChatListAnswer.self)awaitMainActor.run { ChatBooks.fanTiles = answer.fan }return answer }func thread(_ ask: ChatThreadAsk) asyncthrows -> ChatThreadAnswer {tryawait core.call(ChatMethod.thread, ask, as: ChatThreadAnswer.self) }func compose(_ ask: ChatComposeAsk) asyncthrows -> ChatComposeAnswer {tryawait core.call(ChatMethod.compose, ask, as: ChatComposeAnswer.self) }func act(_ ask: ChatActAsk) asyncthrows -> ChatActAnswer {tryawait core.call(ChatMethod.act, ask, as: ChatActAnswer.self) }func decide(_ thread: String, _ method: String) asyncthrows { _ = tryawait core.call(method, Thread(thread: thread), as: Anything.self) }func themes() asyncthrows -> ChatThemesAnswer {tryawait core.call(ChatMethod.themes, [String: String](), as: ChatThemesAnswer.self) }func choose(theme: String, dark: Bool) asyncthrows -> ChatThemesAnswer {tryawait core.call(ChatSettingsMethod.theme, Theme(theme: theme, dark: dark), as: ChatThemesAnswer.self) }func setText(_ id: String) asyncthrows -> ChatThemesAnswer {tryawait core.call(ChatSettingsMethod.text, Value(value: id), as: ChatThemesAnswer.self) }func setGround(_ ground: String) asyncthrows -> ChatThemesAnswer {tryawait core.call(ChatSettingsMethod.ground, Ground(ground: ground), as: ChatThemesAnswer.self) }func calls(after: String?) asyncthrows -> ChatCallsAnswer {tryawait core.call(ChatMethod.calls, After(after: after), as: ChatCallsAnswer.self) }func flush() async {await chat?.flush() }func picture(media: String?, message: String?, index: Int?) async -> URL? {guardlet message else { returnnil }let dir = FileManager.default.temporaryDirectory.appendingPathComponent("chat-pictures", isDirectory: true).pathguardlet path = try? await core.call(ChatMethod.picture, Picture(message: message, index: index ?? 0, dir: dir), as: Path.self).pathelse { returnnil }return URL(fileURLWithPath: path) }func findPicture(message: String, index: Int) async -> ChatPictureFound {let dir = FileManager.default.temporaryDirectory.appendingPathComponent("chat-pictures", isDirectory: true).pathdo {let opened = tryawait core.call(ChatMethod.picture, Picture(message: message, index: index, dir: dir), as: Opened.self)let url = URL(fileURLWithPath: opened.path)// A picture with no preview yet (sent before previews, or imported) gets its own from this file.if opened.previewWanted == true { awaitChatAhead.shared.preview(message: message, index: index, file: url, book: self) }return .file(url) } catchlet refusal asCottonCallError {return .of(code: refusal.code) } catch {return .notYet } }func ahead(thread: String, messages: [String]) async { _ = try? await core.call(ChatMethod.ahead, Ahead(thread: thread, messages: messages), as: Anything.self) }func warm(constrained: Bool) async -> Int { (try? await core.call(ChatMethod.warm, Warm(constrained: constrained), as: Warmed.self))?.fetched ?? 0 }func previewsWanted() async -> [ChatPreviewWanted] { (try? await core.call(ChatMethod.previews, [String: String](), as: Wanted.self))?.items ?? [] }func setPreviews(_ made: [ChatPreviewMade]) async { _ = try? await core.call(ChatMethod.preview, Made(items: made), as: Anything.self) }func voiceSpeed() async -> Double { (try? await core.call(ChatMethod.settings, [String: String](), as: VoiceSettings.self))?.voiceSpeed ?? 1 }func setVoiceSpeed(_ speed: Double) async { _ = try? await core.call(ChatMethod.settings, VoiceSpeed(voiceSpeed: speed), as: Anything.self) }func waveformsWanted() async -> [ChatPreviewWanted] { (try? await core.call(ChatMethod.waveforms, [String: String](), as: Wanted.self))?.items ?? [] }func setWaveforms(_ made: [ChatWaveformMade]) async { _ = try? await core.call(ChatMethod.waveform, Waves(items: made), as: Anything.self) }func linkCard(thread: String, url: String, page: String) async -> ChatLinkCardAnswer? { (try? await core.call(ChatMethod.linkCard, LinkPage(thread: thread, url: url, page: page), as: ChatLinkCardAnswer.self)) .flatMap { $0.title == nil ? nil : $0 } }func file(message: String, index: Int) asyncthrows -> ChatFileAnswer {// A caches folder: the system may take it back, and `chat.file` writes it again.let dir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("chat-files", isDirectory: true).pathreturntryawait core.call(ChatMethod.file, Picture(message: message, index: index, dir: dir), as: ChatFileAnswer.self) }func changes() -> AsyncStream<ChatChange> {AsyncStream { continuation inlet token = NotificationCenter.default.addObserver(forName: .cottonChatLanded, object: nil, queue: nil) { note iniflet thread = note.userInfo?["thread"] as? String { continuation.yield(.arrived(thread: thread)) } }// A read here answers its row; one from another phone names only its thread.let read = NotificationCenter.default.addObserver(forName: .cottonChatRead, object: nil, queue: nil) { note iniflet row = note.userInfo?["row"] as? ChatListRow { continuation.yield(.row(row)) } elseiflet thread = note.userInfo?["thread"] as? String { continuation.yield(.read(thread: thread)) } }let box = ObserverBox(token)let readBox = ObserverBox(read) continuation.onTermination = { _ inNotificationCenter.default.removeObserver(box.token)NotificationCenter.default.removeObserver(readBox.token) } } }privatefinalclassObserverBox: @unchecked Sendable {let token: any NSObjectProtocolinit(_ token: any NSObjectProtocol) { self.token = token } }}/// A message's picture asked of the book once at a time, and never again/// in a storm. Gone is the core's word only: the store said it does not hold/// the file and the message is past its first minutes (`ChatMediaPart.gone`,/// or `chat.picture` refused `not_found`), or its bytes did not open; it is/// then not asked again for 30 seconds, then 2, 10 and 60 minutes, however/// often it is drawn. A picture on its way (still going up, new and not/// landed yet, no connection) is never drawn as gone: it is asked again after/// 2, 5, 15, 30 seconds, then each minute, while its tile stands. A tile/// drawn again while one try is out waits for that try.@MainActor @ObservablefinalclassChatPictureTries {staticlet shared = ChatPictureTries()/// The pictures the core said are gone, or whose bytes did not open: drawn as not available.private(set) var gone: Set<String> = []privatestructWait { var tries: Int; var until: ContinuousClock.Instant; var gone: Bool } @ObservationIgnored privatevar waits: [String: Wait] = [:] @ObservationIgnored privatevar out: [String: Task<ChatPictureFound, Never>] = [:]staticlet backoff: [Duration] = [.seconds(30), .seconds(120), .seconds(600), .seconds(3_600)]staticvar soon: [Duration] = [.seconds(2), .seconds(5), .seconds(15), .seconds(30), .seconds(60)]staticfunc key(_ message: String, _ index: Int) -> String { "\(message)#\(index)" }/// One try, or what the last one found while its wait runs.func find(message: String, index: Int, book: any ChatBook) async -> ChatPictureFound {let key = Self.key(message, index)iflet running = out[key] { returnawait running.value }iflet wait = waits[key], ContinuousClock.now < wait.until { return wait.gone ? .gone : .notYet }let running = Task { await book.findPicture(message: message, index: index) } out[key] = runninglet found = await running.value out[key] = nilswitch found {case .file: waits[key] = nil; gone.remove(key)case .gone: failed(key)case .notYet: later(key) }return found }/// The picture's file, from one try, or nil while its wait runs.func url(message: String, index: Int, book: any ChatBook) async -> URL? {await find(message: message, index: index, book: book).url }/// The picture's file, asked again after each wait while it is on its way; nil once it is gone/// or the asking task ends (its tile went).func file(message: String, index: Int, book: any ChatBook) async -> URL? {while !Task.isCancelled {switchawait find(message: message, index: index, book: book) {case .file(let url): return urlcase .gone: returnnilcase .notYet:let until = waits[Self.key(message, index)]?.until ?? ContinuousClock.now + Self.soon[0]try? awaitTask.sleep(until: max(until, ContinuousClock.now + .milliseconds(200)), clock: .continuous) } }returnnil }/// The file came but did not open as a picture: not available, as a missing one.func unopened(message: String, index: Int) { failed(Self.key(message, index)) }privatefunc failed(_ key: String) {let tries = (waits[key].map { $0.gone ? $0.tries : 0 } ?? 0) + 1 waits[key] = Wait(tries: tries, until: ContinuousClock.now + Self.backoff[min(tries, Self.backoff.count) - 1], gone: true) gone.insert(key) }privatefunc later(_ key: String) {let tries = (waits[key].map { $0.gone ? 0 : $0.tries } ?? 0) + 1 waits[key] = Wait(tries: tries, until: ContinuousClock.now + Self.soon[min(tries, Self.soon.count) - 1], gone: false) gone.remove(key) }}/// Pictures decoded off the main thread at the size they are drawn, kept/// while the app runs.actor ChatPictures {staticlet shared = ChatPictures()privatelet cache = NSCache<NSString, UIImage>()/// Each message's picture as last drawn, by message, index and side: read on the drawing thread, so a cell drawn/// again (or the chat opened again) shows it on its first frame. NSCache is safe from any thread. nonisolated(unsafe) privatestaticlet drawnCache: NSCache<NSString, UIImage> = {let cache = NSCache<NSString, UIImage>() cache.countLimit = 300return cache }() nonisolated staticfunc drawn(_ key: String, side: CGFloat) -> UIImage? { drawnCache.object(forKey: "\(key)#\(Int(side))"as NSString) } nonisolated staticfunc remember(_ key: String, side: CGFloat, _ image: UIImage) { drawnCache.setObject(image, forKey: "\(key)#\(Int(side))"as NSString) }func image(_ url: URL, side: CGFloat) async -> UIImage? {let key = "\(url.path)#\(Int(side))"as NSStringiflet hit = cache.object(forKey: key) { return hit }let image: UIImage? = awaitTask.detached(priority: .userInitiated) {guardlet source = CGImageSourceCreateWithURL(url as CFURL, nil) else { returnnil }let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: max(1, Int(side * 3))]guardlet cg = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { returnnil }return UIImage(cgImage: cg).preparingForDisplay() }.valueiflet image { cache.setObject(image, forKey: key) }return image }/// A tiny base64 preview, decoded once.func preview(_ base64: String) -> UIImage? {let key = "p:\(base64.hashValue)"as NSStringiflet hit = cache.object(forKey: key) { return hit }guardlet data = Data(base64Encoded: base64), let image = UIImage(data: data) else { returnnil } cache.setObject(image, forKey: key)return image }}#endif