// Pictures at once (CONTRACT.md "Pictures at once", 23 Nov 2026): every// picture's preview is drawn on the first frame at its true size, and the// full pictures are on the phone before the reader reaches them. The rules// (what is kept, for how long, what comes first) are the core's; this file// only tells it what the screen shows and when the network allows://// - `chat.ahead { thread, messages }` as the open chat scrolls (ChatThreadTable);// - `chat.warm { constrained }` from the chat list and when the app comes to// the front, in a background task, nothing in Low Data Mode;// - `chat.previews` / `chat.preview`: a preview made here for a picture that// has none (sent before previews, or imported), written into its message;// - a picture picked to send carries its preview (`ChatOutbox.attachment`).#if os(iOS)importFoundationimportImageIOimportNetworkimport UIKitimportUniformTypeIdentifiers/// Whether the phone is in Low Data Mode (`NWPath.isConstrained`): then nothing is fetched in the background.finalclassChatLowData: @unchecked Sendable {staticlet shared = ChatLowData()privatelet monitor = NWPathMonitor()privatelet lock = NSLock()privatevar low = falseprivateinit() { monitor.pathUpdateHandler = { [weakself] path inguardletselfelse { return }self.lock.withLock { self.low = path.isConstrained } } monitor.start(queue: DispatchQueue(label: "com.cottondb.chat.lowdata", qos: .utility)) }var constrained: Bool {// A development launch may say the phone is in Low Data Mode (`-chat-low-data YES`).ifChatDevArguments.lowData { returntrue }return lock.withLock { low } }}enumChatDevArguments { #if COTTON_DEVstaticvar lowData: Bool { UserDefaults.standard.bool(forKey: "chat-low-data") } #elsestaticvar lowData: Bool { false } #endif}/// A picture's preview: at most 32 points a side, a JPEG of at most 2 KB, as base64 (the core's `PREVIEW_MAX`).enumChatPreviewMaker {staticlet side = 32staticlet most = 2_000staticfunc make(_ url: URL) -> String? {guardlet source = CGImageSourceCreateWithURL(url as CFURL, nil) else { returnnil }let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: side]guardlet small = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { returnnil }for quality in [0.6, 0.4, 0.25, 0.1] {let data = NSMutableData()guardlet out = CGImageDestinationCreateWithData(data as CFMutableData, UTType.jpeg.identifier as CFString, 1, nil) else { returnnil } CGImageDestinationAddImage(out, small, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)guard CGImageDestinationFinalize(out) else { returnnil }if data.length <= most { return (data asData).base64EncodedString() } }returnnil }}/// What the screens tell the core, each off the main thread and never twice at once.@MainActorfinalclassChatAhead {staticlet shared = ChatAhead()privatevar scrolling: Task<Void, Never>?privatevar shown: [String] = []privatevar warming: Task<Void, Never>?privatevar warmedAt: ContinuousClock.Instant?privatevar previewing: Task<Void, Never>?privatevar wanted: Set<String> = []/// The open chat shows these messages: their pictures and those on each side come onto the phone. Asked a/// moment after the scroll settles on them, so a fling asks once, not each frame.func scrolled(thread: String, messages: [String], book: any ChatBook) {guard !messages.isEmpty, messages != shown else { return } shown = messages scrolling?.cancel() scrolling = Task { @MainActor intry? awaitTask.sleep(for: .milliseconds(120))guard !Task.isCancelled else { return }awaitTask.detached(priority: .utility) { await book.ahead(thread: thread, messages: messages) }.valueself.previews(book: book) } }/// The chat list's warm: the top chats' newest pictures, then the last thirty days, in the background, at most/// once in half a minute; nothing in Low Data Mode (the previews came with the words).func warm(book: any ChatBook, force: Bool = false) {if warming != nil { return }if !force, let at = warmedAt, ContinuousClock.now - at < .seconds(30) { return } warmedAt = .nowlet constrained = ChatLowData.shared.constrained warming = Task { @MainActor in// Carried on for a little while if the person leaves the app (the system's background time).let background = UIApplication.shared.beginBackgroundTask(withName: "chat-warm")awaitTask.detached(priority: .background) {// A few rounds: each brings at most the core's WARM_LIMIT.for _ in0..<5 {ifawait book.warm(constrained: constrained) == 0 { break } } }.valueif background != .invalid { UIApplication.shared.endBackgroundTask(background) }self.warming = nilself.previews(book: book) } }/// One picture just drawn has no preview: made from its file and written into its message.func preview(message: String, index: Int, file: URL, book: any ChatBook) {let key = "\(message)#\(index)"guard wanted.insert(key).inserted else { return }Task.detached(priority: .utility) {guardlet preview = ChatPreviewMaker.make(file) else { return }await book.setPreviews([ChatPreviewMade(message: message, index: index, preview: preview)]) } }/// Previews for the pictures on this phone that have none, a page at a time.func previews(book: any ChatBook) {guard previewing == nilelse { return } previewing = Task { @MainActor inawaitTask.detached(priority: .background) {for _ in0..<10 {let wanted = await book.previewsWanted()if wanted.isEmpty { break }let made = wanted.compactMap { w inChatPreviewMaker.make(URL(fileURLWithPath: w.path)).map { ChatPreviewMade(message: w.message, index: w.index, preview: $0) } }if made.isEmpty { break }await book.setPreviews(made)if made.count < wanted.count { break } }// Voice messages with no waveform (sent by an older phone, or imported) get theirs from this phone.for _ in0..<5 {let wanted = await book.waveformsWanted()if wanted.isEmpty { break }let made = wanted.compactMap { w inChatVoicePeaks.of(URL(fileURLWithPath: w.path)).map { ChatWaveformMade(message: w.message, index: w.index, waveform: $0) } }if made.isEmpty { break }await book.setWaveforms(made)if made.count < wanted.count { break } } }.valueself.previewing = nil } }}/// A picture on this phone with no preview yet (`chat.previews`).structChatPreviewWanted: Codable, Equatable, Sendable {var message: Stringvar index: Intvar path: String}/// A voice message's waveform read here from its file (`chat.waveform`), 0…1, at most 64.structChatWaveformMade: Codable, Equatable, Sendable {var message: Stringvar index: Intvar waveform: [Double]}/// A preview made here (`chat.preview`).structChatPreviewMade: Codable, Equatable, Sendable {var message: Stringvar index: Intvar preview: String}/// Previews decoded once, at once, on the thread that draws them: a tile's first frame is never a blank box.enumChatPreviewImages { nonisolated(unsafe) privatestaticlet cache: NSCache<NSString, UIImage> = {let cache = NSCache<NSString, UIImage>() cache.countLimit = 4_000return cache }()staticfunc image(_ base64: String) -> UIImage? {let key = base64 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