// 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) import Foundation import ImageIO import Network import UIKit import UniformTypeIdentifiers /// Whether the phone is in Low Data Mode (`NWPath.isConstrained`): then nothing is fetched in the background. final class ChatLowData: @unchecked Sendable { static let shared = ChatLowData() private let monitor = NWPathMonitor() private let lock = NSLock() private var low = false private init() { monitor.pathUpdateHandler = { [weak self] path in guard let self else { 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`). if ChatDevArguments.lowData { return true } return lock.withLock { low } } } enum ChatDevArguments { #if COTTON_DEV static var lowData: Bool { UserDefaults.standard.bool(forKey: "chat-low-data") } #else static var 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`). enum ChatPreviewMaker { static let side = 32 static let most = 2_000 static func make(_ url: URL) -> String? { guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil } let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: side] guard let small = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil } for quality in [0.6, 0.4, 0.25, 0.1] { let data = NSMutableData() guard let out = CGImageDestinationCreateWithData(data as CFMutableData, UTType.jpeg.identifier as CFString, 1, nil) else { return nil } CGImageDestinationAddImage(out, small, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary) guard CGImageDestinationFinalize(out) else { return nil } if data.length <= most { return (data as Data).base64EncodedString() } } return nil } } /// What the screens tell the core, each off the main thread and never twice at once. @MainActor final class ChatAhead { static let shared = ChatAhead() private var scrolling: Task? private var shown: [String] = [] private var warming: Task? private var warmedAt: ContinuousClock.Instant? private var previewing: Task? private var wanted: Set = [] /// 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 in try? await Task.sleep(for: .milliseconds(120)) guard !Task.isCancelled else { return } await Task.detached(priority: .utility) { await book.ahead(thread: thread, messages: messages) }.value self.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 = .now let 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") await Task.detached(priority: .background) { // A few rounds: each brings at most the core's WARM_LIMIT. for _ in 0..<5 { if await book.warm(constrained: constrained) == 0 { break } } }.value if background != .invalid { UIApplication.shared.endBackgroundTask(background) } self.warming = nil self.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) { guard let 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 == nil else { return } previewing = Task { @MainActor in await Task.detached(priority: .background) { for _ in 0..<10 { let wanted = await book.previewsWanted() if wanted.isEmpty { break } let made = wanted.compactMap { w in ChatPreviewMaker.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 _ in 0..<5 { let wanted = await book.waveformsWanted() if wanted.isEmpty { break } let made = wanted.compactMap { w in ChatVoicePeaks.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 } } }.value self.previewing = nil } } } /// A picture on this phone with no preview yet (`chat.previews`). struct ChatPreviewWanted: Codable, Equatable, Sendable { var message: String var index: Int var path: String } /// A voice message's waveform read here from its file (`chat.waveform`), 0…1, at most 64. struct ChatWaveformMade: Codable, Equatable, Sendable { var message: String var index: Int var waveform: [Double] } /// A preview made here (`chat.preview`). struct ChatPreviewMade: Codable, Equatable, Sendable { var message: String var index: Int var preview: String } /// Previews decoded once, at once, on the thread that draws them: a tile's first frame is never a blank box. enum ChatPreviewImages { nonisolated(unsafe) private static let cache: NSCache = { let cache = NSCache() cache.countLimit = 4_000 return cache }() static func image(_ base64: String) -> UIImage? { let key = base64 as NSString if let hit = cache.object(forKey: key) { return hit } guard let data = Data(base64Encoded: base64), let image = UIImage(data: data) else { return nil } cache.setObject(image, forKey: key) return image } } #endif