import Foundation import UIKit @MainActor final class InlineImageStore { struct Entry { let image: UIImage? let gifData: Data? let borderColors: AvatarRingColors } private final class Box { let entry: Entry init(_ entry: Entry) { self.entry = entry } } private struct Download { let id: UUID let task: Task } private struct Decode { let id: UUID let task: Task } private let cache = NSCache() private let loader: @Sendable (URL) async throws -> Data private var downloads: [URL: Download] = [:] private var decodes: [URL: Decode] = [:] private var generation = 0 init(loader: (@Sendable (URL) async throws -> Data)? = nil) { self.loader = loader ?? Self.download cache.totalCostLimit = 192 * 1024 * 1024 cache.countLimit = 500 } func cachedImage(for url: URL) -> Entry? { cache.object(forKey: url as NSURL)?.entry } func load(_ url: URL, decodeGIF: Bool) async -> Entry? { let currentGeneration = generation var entry = cachedImage(for: url) if entry == nil { let download = pendingDownload(for: url) let data: Data do { data = try await download.task.value } catch { if downloads[url]?.id == download.id { downloads[url] = nil } return nil } guard generation == currentGeneration else { return nil } entry = cachedImage(for: url) if entry == nil, RemoteImageDecoder.isGIF(data) { let raw = Entry(image: nil, gifData: data, borderColors: .fallback) put(raw, for: url) entry = raw } if entry == nil { let result = await decodedEntry(data, gifData: nil, for: url, generation: currentGeneration) if downloads[url]?.id == download.id { downloads[url] = nil } return result } if downloads[url]?.id == download.id { downloads[url] = nil } } guard let entry else { return nil } guard decodeGIF, entry.image == nil, let data = entry.gifData else { return entry } return await decodedEntry(data, gifData: data, for: url, generation: currentGeneration) } private func pendingDownload(for url: URL) -> Download { if let existing = downloads[url] { return existing } let loader = self.loader let download = Download(id: UUID(), task: Task.detached { try await loader(url) }) downloads[url] = download return download } func clear() { generation &+= 1 downloads.values.forEach { $0.task.cancel() } decodes.values.forEach { $0.task.cancel() } downloads.removeAll() decodes.removeAll() cache.removeAllObjects() } private func decodedEntry(_ data: Data, gifData: Data?, for url: URL, generation: Int) async -> Entry? { let decode: Decode if let existing = decodes[url] { decode = existing } else { decode = Decode(id: UUID(), task: Task { await ImageDecodeQueue.shared.decodeInline(data) }) decodes[url] = decode } let decoded = await decode.task.value guard self.generation == generation else { return nil } if decodes[url]?.id == decode.id { decodes[url] = nil } guard let decoded else { cache.removeObject(forKey: url as NSURL) return nil } if let existing = cachedImage(for: url), existing.image != nil { return existing } let entry = Entry(image: decoded.image, gifData: gifData, borderColors: decoded.borderColors) put(entry, for: url) return entry } private func put(_ entry: Entry, for url: URL) { var cost = entry.gifData?.count ?? 0 if let image = entry.image { let frames = image.images ?? [image] for frame in frames { if let cgImage = frame.cgImage { let (bytes, overflow) = cgImage.bytesPerRow.multipliedReportingOverflow(by: cgImage.height) let (sum, sumOverflow) = cost.addingReportingOverflow(bytes) cost = overflow || sumOverflow ? Int.max : sum } } } cache.setObject(Box(entry), forKey: url as NSURL, cost: cost) } @Sendable private nonisolated static func download(_ url: URL) async throws -> Data { if url.scheme?.lowercased() == "data", ProcessInfo.processInfo.arguments.contains("-ui-testing") { let parts = url.absoluteString.split(separator: ",", maxSplits: 1) guard parts.count == 2, let data = Data(base64Encoded: String(parts[1])) else { throw URLError(.badURL) } try GIFDownload.validate(data) return data } let (data, response) = try await GIFDownload.load(url) guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else { throw URLError(.badServerResponse) } return data } }