1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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<Data, Error>
}
private struct Decode {
let id: UUID
let task: Task<ImageDecodeQueue.InlineImage?, Never>
}
private let cache = NSCache<NSURL, Box>()
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
}
}