@onekeyfe/react-native-image 6.7.0-4 → 6.7.0-40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/OneKeyImage.podspec +1 -1
- package/README.md +12 -0
- package/android/build.gradle +3 -1
- package/android/src/main/AndroidManifest.xml +7 -1
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyBlockieAvatarLoader.kt +1 -1
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyIcon.kt +93 -0
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageCache.kt +12 -0
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageGlideModule.kt +17 -0
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageGlideRegistry.kt +19 -1
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImagePackage.kt +2 -1
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageSafety.kt +1 -1
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyMediaPreviewCache.kt +199 -0
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyNamedSVG.kt +217 -0
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeySVG.kt +264 -0
- package/android/src/test/java/com/margelo/nitro/onekeyimage/OneKeyBlockieAvatarLoaderTest.kt +2 -1
- package/android/src/test/java/com/margelo/nitro/onekeyimage/OneKeyImageSafetyTest.kt +1 -1
- package/android/src/test/java/com/margelo/nitro/onekeyimage/OneKeySVGForeignObjectTest.kt +130 -0
- package/ios/OneKeyAvatarImageLoader.swift +1 -1
- package/ios/OneKeyIcon.swift +90 -0
- package/ios/OneKeyImageCache.swift +23 -5
- package/ios/OneKeyImageCoderBridge.h +4 -0
- package/ios/OneKeyImageCoderBridge.m +361 -1
- package/ios/OneKeyImageRequestContext.swift +8 -3
- package/ios/OneKeyMediaPreviewCache.swift +209 -0
- package/ios/OneKeyNamedSVG.swift +282 -0
- package/ios/tests/OneKeyIconTests.swift +484 -0
- package/ios/tests/OneKeyImageInfrastructureTests.swift +25 -3
- package/ios/tests/OneKeyMediaPreviewCacheTests.swift +139 -0
- package/ios/tests/OneKeySVGForeignObjectTests.swift +267 -0
- package/lib/module/OneKeyIcon.nitro.js +4 -0
- package/lib/module/icon/assetUrls.js +13 -0
- package/lib/module/icon/dom.js +21 -0
- package/lib/module/icon/index.js +29 -0
- package/lib/module/icon/index.web.js +32 -0
- package/lib/module/icon/props.js +22 -0
- package/lib/module/package.json +6 -1
- package/lib/nitrogen/generated/android/c++/JHybridOneKeyIconSpec.cpp +67 -0
- package/lib/nitrogen/generated/android/c++/JHybridOneKeyIconSpec.hpp +66 -0
- package/lib/nitrogen/generated/android/c++/views/JHybridOneKeyIconStateUpdater.cpp +79 -0
- package/lib/nitrogen/generated/android/c++/views/JHybridOneKeyIconStateUpdater.hpp +54 -0
- package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/HybridOneKeyIconSpec.kt +65 -0
- package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/views/HybridOneKeyIconManager.kt +96 -0
- package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/views/HybridOneKeyIconStateUpdater.kt +23 -0
- package/lib/nitrogen/generated/android/onekeyimage+autolinking.cmake +4 -0
- package/lib/nitrogen/generated/android/onekeyimageOnLoad.cpp +18 -0
- package/lib/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Bridge.cpp +17 -0
- package/lib/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Bridge.hpp +32 -15
- package/lib/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Umbrella.hpp +5 -0
- package/lib/nitrogen/generated/ios/OneKeyImageAutolinking.mm +8 -0
- package/lib/nitrogen/generated/ios/OneKeyImageAutolinking.swift +12 -0
- package/lib/nitrogen/generated/ios/c++/HybridOneKeyIconSpecSwift.cpp +11 -0
- package/lib/nitrogen/generated/ios/c++/HybridOneKeyIconSpecSwift.hpp +89 -0
- package/lib/nitrogen/generated/ios/c++/views/HybridOneKeyIconComponent.mm +150 -0
- package/lib/nitrogen/generated/ios/swift/HybridOneKeyIconSpec.swift +56 -0
- package/lib/nitrogen/generated/ios/swift/HybridOneKeyIconSpec_cxx.swift +193 -0
- package/lib/nitrogen/generated/shared/c++/HybridOneKeyIconSpec.cpp +24 -0
- package/lib/nitrogen/generated/shared/c++/HybridOneKeyIconSpec.hpp +66 -0
- package/lib/nitrogen/generated/shared/c++/views/HybridOneKeyIconComponent.cpp +36 -0
- package/lib/nitrogen/generated/shared/c++/views/HybridOneKeyIconComponent.hpp +88 -0
- package/lib/nitrogen/generated/shared/json/OneKeyIconConfig.json +11 -0
- package/lib/typescript/src/OneKeyIcon.nitro.d.ts +7 -0
- package/lib/typescript/src/icon/assetUrls.d.ts +2 -0
- package/lib/typescript/src/icon/dom.d.ts +3 -0
- package/lib/typescript/src/icon/index.d.ts +12 -0
- package/lib/typescript/src/icon/index.web.d.ts +6 -0
- package/lib/typescript/src/icon/props.d.ts +8 -0
- package/lib/typescript/src/index.d.ts +1 -1
- package/nitro.json +10 -0
- package/nitrogen/generated/android/c++/JHybridOneKeyIconSpec.cpp +67 -0
- package/nitrogen/generated/android/c++/JHybridOneKeyIconSpec.hpp +66 -0
- package/nitrogen/generated/android/c++/views/JHybridOneKeyIconStateUpdater.cpp +79 -0
- package/nitrogen/generated/android/c++/views/JHybridOneKeyIconStateUpdater.hpp +54 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/HybridOneKeyIconSpec.kt +65 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/views/HybridOneKeyIconManager.kt +96 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/views/HybridOneKeyIconStateUpdater.kt +23 -0
- package/nitrogen/generated/android/onekeyimage+autolinking.cmake +4 -0
- package/nitrogen/generated/android/onekeyimageOnLoad.cpp +18 -0
- package/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Bridge.cpp +17 -0
- package/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Bridge.hpp +32 -15
- package/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Umbrella.hpp +5 -0
- package/nitrogen/generated/ios/OneKeyImageAutolinking.mm +8 -0
- package/nitrogen/generated/ios/OneKeyImageAutolinking.swift +12 -0
- package/nitrogen/generated/ios/c++/HybridOneKeyIconSpecSwift.cpp +11 -0
- package/nitrogen/generated/ios/c++/HybridOneKeyIconSpecSwift.hpp +89 -0
- package/nitrogen/generated/ios/c++/views/HybridOneKeyIconComponent.mm +150 -0
- package/nitrogen/generated/ios/swift/HybridOneKeyIconSpec.swift +56 -0
- package/nitrogen/generated/ios/swift/HybridOneKeyIconSpec_cxx.swift +193 -0
- package/nitrogen/generated/shared/c++/HybridOneKeyIconSpec.cpp +24 -0
- package/nitrogen/generated/shared/c++/HybridOneKeyIconSpec.hpp +66 -0
- package/nitrogen/generated/shared/c++/views/HybridOneKeyIconComponent.cpp +36 -0
- package/nitrogen/generated/shared/c++/views/HybridOneKeyIconComponent.hpp +88 -0
- package/nitrogen/generated/shared/json/OneKeyIconConfig.json +11 -0
- package/package.json +48 -15
- package/scripts/configure-icon-imports.mjs +7 -0
- package/scripts/icon-fixtures.test.mjs +398 -0
- package/src/OneKeyIcon.nitro.ts +8 -0
- package/src/icon/assetUrls.ts +13 -0
- package/src/icon/dom.ts +21 -0
- package/src/icon/index.tsx +38 -0
- package/src/icon/index.web.tsx +36 -0
- package/src/icon/props.ts +38 -0
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import CryptoKit
|
|
2
|
+
import Foundation
|
|
3
|
+
import ImageIO
|
|
4
|
+
import SDWebImage
|
|
5
|
+
import UIKit
|
|
6
|
+
|
|
7
|
+
/// Native-only process cache. Players remain owned by their view slots.
|
|
8
|
+
public final class OneKeyMediaPreviewCache {
|
|
9
|
+
public static let shared = OneKeyMediaPreviewCache()
|
|
10
|
+
public static func targetEdge(_ pixels: CGFloat) -> Int {
|
|
11
|
+
[128, 256, 512, 1024].first { CGFloat($0) >= pixels } ?? 1024
|
|
12
|
+
}
|
|
13
|
+
public final class Subscription {
|
|
14
|
+
fileprivate var cancelled = false
|
|
15
|
+
fileprivate let key: String
|
|
16
|
+
fileprivate let image: (UIImage) -> Void
|
|
17
|
+
fileprivate let extract: (UUID) -> Void
|
|
18
|
+
fileprivate let revoked: () -> Void
|
|
19
|
+
fileprivate let failure: () -> Void
|
|
20
|
+
fileprivate init(key: String, image: @escaping (UIImage) -> Void, extract: @escaping (UUID) -> Void,
|
|
21
|
+
revoked: @escaping () -> Void, failure: @escaping () -> Void) {
|
|
22
|
+
self.key = key; self.image = image; self.extract = extract; self.revoked = revoked; self.failure = failure
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
private final class Flight {
|
|
26
|
+
let key: String
|
|
27
|
+
let storageKey: String
|
|
28
|
+
let policy: String
|
|
29
|
+
let memoryGeneration: Int
|
|
30
|
+
let diskGeneration: Int
|
|
31
|
+
var subscribers: [Subscription] = []
|
|
32
|
+
var lease: UUID?
|
|
33
|
+
var lookupWorkItem: DispatchWorkItem?
|
|
34
|
+
var timeout: DispatchWorkItem?
|
|
35
|
+
var ready = false
|
|
36
|
+
init(key: String, storageKey: String, policy: String, memory: Int, disk: Int) {
|
|
37
|
+
self.key = key; self.storageKey = storageKey; self.policy = policy
|
|
38
|
+
memoryGeneration = memory; diskGeneration = disk
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
private let cache: SDImageCache
|
|
42
|
+
private let io = DispatchQueue(label: "onekey.media-preview.io", qos: .userInitiated)
|
|
43
|
+
private var flights: [String: Flight] = [:]
|
|
44
|
+
private var queue: [String] = []
|
|
45
|
+
private var active = 0
|
|
46
|
+
private var pendingPersistenceBytes = 0
|
|
47
|
+
private var memoryGeneration = 0
|
|
48
|
+
private var diskGeneration = 0
|
|
49
|
+
init(namespace: String = "onekey-media-preview-v1") {
|
|
50
|
+
let config = SDImageCacheConfig()
|
|
51
|
+
config.maxMemoryCost = 16 * 1024 * 1024; config.maxMemoryCount = 64
|
|
52
|
+
config.maxDiskSize = 128 * 1024 * 1024; config.maxDiskAge = 30 * 24 * 60 * 60
|
|
53
|
+
config.diskCacheExpireType = .accessDate
|
|
54
|
+
cache = SDImageCache(namespace: namespace, diskCacheDirectory: nil, config: config)
|
|
55
|
+
}
|
|
56
|
+
static func storageKey(uri: String, headers: [String: String], edge: Int, fit: String) -> String {
|
|
57
|
+
let normalized: [(String, String)] = headers.map { ($0.key.lowercased(), $0.value) }
|
|
58
|
+
let fields: [(String, String)] = normalized.sorted {
|
|
59
|
+
$0.0 == $1.0 ? $0.1 < $1.1 : $0.0 < $1.0
|
|
60
|
+
}
|
|
61
|
+
let values = ["onekey-media-preview-v1", uri, String(edge), fit] + fields.flatMap { [$0.0, $0.1] }
|
|
62
|
+
let canonical = values.map { "\($0.utf8.count):\($0)" }.joined()
|
|
63
|
+
return SHA256.hash(data: Data(canonical.utf8)).map { String(format: "%02x", $0) }.joined()
|
|
64
|
+
}
|
|
65
|
+
@discardableResult
|
|
66
|
+
public func request(uri: String, headers: [String: String], edge: Int, fit: String, policy: String,
|
|
67
|
+
onImage: @escaping (UIImage) -> Void, onExtract: @escaping (UUID) -> Void,
|
|
68
|
+
onRevoked: @escaping () -> Void, onFailure: @escaping () -> Void) -> Subscription {
|
|
69
|
+
dispatchPrecondition(condition: .onQueue(.main))
|
|
70
|
+
let storageKey = Self.storageKey(uri: uri, headers: headers,
|
|
71
|
+
edge: Self.targetEdge(CGFloat(max(1, edge))), fit: fit)
|
|
72
|
+
let key = "\(storageKey)|\(policy)"
|
|
73
|
+
let subscriber = Subscription(key: key, image: onImage, extract: onExtract, revoked: onRevoked, failure: onFailure)
|
|
74
|
+
if let flight = flights[key] { flight.subscribers.append(subscriber); return subscriber }
|
|
75
|
+
guard flights.count < 130 else {
|
|
76
|
+
DispatchQueue.main.async { if !subscriber.cancelled { subscriber.failure() } }
|
|
77
|
+
return subscriber
|
|
78
|
+
}
|
|
79
|
+
let flight = Flight(key: key, storageKey: storageKey, policy: policy, memory: memoryGeneration, disk: diskGeneration)
|
|
80
|
+
flight.subscribers = [subscriber]; flights[key] = flight
|
|
81
|
+
if permitsMemory(policy), let image = cache.imageFromMemoryCache(forKey: storageKey) {
|
|
82
|
+
DispatchQueue.main.async { [weak self] in self?.finish(flight, image: image) }; return subscriber
|
|
83
|
+
}
|
|
84
|
+
let lookup = DispatchWorkItem { [weak self, weak flight] in
|
|
85
|
+
guard let self, let flight, flight.lookupWorkItem?.isCancelled == false else { return }
|
|
86
|
+
var image: UIImage?
|
|
87
|
+
if self.permitsDisk(policy), let path = self.cache.cachePath(forKey: storageKey) {
|
|
88
|
+
let url = URL(fileURLWithPath: path)
|
|
89
|
+
let accessDate = try? url.resourceValues(forKeys: [.contentAccessDateKey]).contentAccessDate
|
|
90
|
+
if let accessDate, accessDate > Date().addingTimeInterval(-self.cache.config.maxDiskAge),
|
|
91
|
+
let file = FileHandle(forReadingAtPath: path) {
|
|
92
|
+
defer { try? file.close() }
|
|
93
|
+
if let data = try? file.read(upToCount: 8 * 1024 * 1024 + 1), data.count <= 8 * 1024 * 1024,
|
|
94
|
+
let source = CGImageSourceCreateWithData(data as CFData, nil),
|
|
95
|
+
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
|
|
96
|
+
let width = properties[kCGImagePropertyPixelWidth] as? Int,
|
|
97
|
+
let height = properties[kCGImagePropertyPixelHeight] as? Int,
|
|
98
|
+
(1...1024).contains(width), (1...1024).contains(height) {
|
|
99
|
+
let options = [kCGImageSourceShouldCacheImmediately: true] as CFDictionary
|
|
100
|
+
image = CGImageSourceCreateImageAtIndex(source, 0, options).map { UIImage(cgImage: $0) }
|
|
101
|
+
}
|
|
102
|
+
if image != nil {
|
|
103
|
+
try? (url as NSURL).setResourceValue(Date(), forKey: .contentAccessDateKey)
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if image == nil { self.cache.removeImageFromDisk(forKey: storageKey) }
|
|
107
|
+
}
|
|
108
|
+
DispatchQueue.main.async {
|
|
109
|
+
guard self.flights[key] === flight else { return }
|
|
110
|
+
if let image, flight.diskGeneration == self.diskGeneration {
|
|
111
|
+
if self.permitsMemory(policy), flight.memoryGeneration == self.memoryGeneration {
|
|
112
|
+
self.cache.storeImage(toMemory: image, forKey: storageKey)
|
|
113
|
+
}
|
|
114
|
+
self.finish(flight, image: image)
|
|
115
|
+
} else { flight.ready = true; self.queue.append(key); self.pump() }
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
flight.lookupWorkItem = lookup
|
|
119
|
+
io.async(execute: lookup)
|
|
120
|
+
return subscriber
|
|
121
|
+
}
|
|
122
|
+
public func cancel(_ subscription: Subscription?) {
|
|
123
|
+
dispatchPrecondition(condition: .onQueue(.main))
|
|
124
|
+
guard let subscription else { return }
|
|
125
|
+
subscription.cancelled = true
|
|
126
|
+
guard let flight = flights[subscription.key],
|
|
127
|
+
let index = flight.subscribers.firstIndex(where: { $0 === subscription }) else { return }
|
|
128
|
+
let owned = index == 0 && flight.lease != nil
|
|
129
|
+
flight.subscribers.remove(at: index)
|
|
130
|
+
if owned {
|
|
131
|
+
flight.timeout?.cancel(); flight.timeout = nil; flight.lease = nil; active -= 1; subscription.revoked()
|
|
132
|
+
}
|
|
133
|
+
if flight.subscribers.isEmpty {
|
|
134
|
+
flight.lookupWorkItem?.cancel()
|
|
135
|
+
flights.removeValue(forKey: flight.key); queue.removeAll { $0 == flight.key }
|
|
136
|
+
} else if owned { queue.insert(flight.key, at: 0) }
|
|
137
|
+
pump()
|
|
138
|
+
}
|
|
139
|
+
public func fail(_ lease: UUID) {
|
|
140
|
+
dispatchPrecondition(condition: .onQueue(.main))
|
|
141
|
+
guard let flight = flights.values.first(where: { $0.lease == lease }) else { return }; finish(flight, image: nil)
|
|
142
|
+
}
|
|
143
|
+
/// Producers submit bounded, orientation-normalized pixels, never an active player.
|
|
144
|
+
public func complete(_ lease: UUID, image: UIImage) {
|
|
145
|
+
dispatchPrecondition(condition: .onQueue(.main))
|
|
146
|
+
guard let flight = flights.values.first(where: { $0.lease == lease }) else { return }
|
|
147
|
+
guard image.size.width > 0, image.size.height > 0,
|
|
148
|
+
image.size.width * image.scale <= 1024, image.size.height * image.scale <= 1024 else {
|
|
149
|
+
finish(flight, image: nil); return
|
|
150
|
+
}
|
|
151
|
+
if permitsMemory(flight.policy), flight.memoryGeneration == memoryGeneration {
|
|
152
|
+
cache.storeImage(toMemory: image, forKey: flight.storageKey)
|
|
153
|
+
}
|
|
154
|
+
finish(flight, image: image)
|
|
155
|
+
let cost = Int(image.size.width * image.scale) * Int(image.size.height * image.scale) * 4
|
|
156
|
+
guard permitsDisk(flight.policy), pendingPersistenceBytes + cost <= 16 * 1024 * 1024 else { return }
|
|
157
|
+
pendingPersistenceBytes += cost
|
|
158
|
+
io.async { [weak self] in
|
|
159
|
+
guard let self else { return }
|
|
160
|
+
let data = image.pngData()
|
|
161
|
+
DispatchQueue.main.async {
|
|
162
|
+
guard flight.diskGeneration == self.diskGeneration, let data, data.count <= 8 * 1024 * 1024 else {
|
|
163
|
+
self.pendingPersistenceBytes -= cost; return
|
|
164
|
+
}
|
|
165
|
+
// Writes and clears share this queue, closing the generation-check/write race.
|
|
166
|
+
self.io.async {
|
|
167
|
+
self.cache.storeImageData(toDisk: data, forKey: flight.storageKey)
|
|
168
|
+
self.cache.deleteOldFiles(completionBlock: nil)
|
|
169
|
+
DispatchQueue.main.async { self.pendingPersistenceBytes -= cost }
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
public func clearMemory() {
|
|
175
|
+
dispatchPrecondition(condition: .onQueue(.main)); memoryGeneration &+= 1; cache.clearMemory()
|
|
176
|
+
}
|
|
177
|
+
public func clearDisk(completion: @escaping () -> Void) {
|
|
178
|
+
dispatchPrecondition(condition: .onQueue(.main)); diskGeneration &+= 1
|
|
179
|
+
io.async { [self] in
|
|
180
|
+
let cleared = DispatchSemaphore(value: 0)
|
|
181
|
+
cache.clearDisk { cleared.signal() }
|
|
182
|
+
cleared.wait()
|
|
183
|
+
DispatchQueue.main.async { completion() }
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
private func permitsMemory(_ policy: String) -> Bool { policy == "memory" || policy == "memory-disk" }
|
|
187
|
+
private func permitsDisk(_ policy: String) -> Bool { policy == "disk" || policy == "memory-disk" }
|
|
188
|
+
private func pump() {
|
|
189
|
+
while active < 2, !queue.isEmpty {
|
|
190
|
+
let key = queue.removeFirst()
|
|
191
|
+
guard let flight = flights[key], flight.ready, flight.lease == nil, let owner = flight.subscribers.first else { continue }
|
|
192
|
+
let lease = UUID(); flight.lease = lease; active += 1
|
|
193
|
+
let timeout = DispatchWorkItem { [weak self, weak flight] in
|
|
194
|
+
guard let self, let flight, flight.lease == lease else { return }; self.finish(flight, image: nil)
|
|
195
|
+
}
|
|
196
|
+
flight.timeout = timeout; DispatchQueue.main.asyncAfter(deadline: .now() + 10, execute: timeout); owner.extract(lease)
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
private func finish(_ flight: Flight, image: UIImage?) {
|
|
200
|
+
guard flights[flight.key] === flight else { return }
|
|
201
|
+
flight.lookupWorkItem?.cancel()
|
|
202
|
+
flights.removeValue(forKey: flight.key); queue.removeAll { $0 == flight.key }
|
|
203
|
+
if flight.lease != nil { active -= 1; flight.subscribers.first?.revoked() }
|
|
204
|
+
flight.timeout?.cancel(); flight.lease = nil
|
|
205
|
+
let subscribers = flight.subscribers; flight.subscribers = []
|
|
206
|
+
for subscriber in subscribers where !subscriber.cancelled { if let image { subscriber.image(image) } else { subscriber.failure() } }
|
|
207
|
+
pump()
|
|
208
|
+
}
|
|
209
|
+
}
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import UIKit
|
|
3
|
+
|
|
4
|
+
private final class OneKeyIconBundleToken: NSObject {}
|
|
5
|
+
|
|
6
|
+
@objc(OneKeyNamedSVGBridge)
|
|
7
|
+
internal final class OneKeyNamedSVGBridge: NSObject {
|
|
8
|
+
@objc(cancelWithOwner:)
|
|
9
|
+
static func cancel(owner: AnyObject) {
|
|
10
|
+
OneKeyNamedSVG.shared.cancel(owner: owner)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
@objc(requestWithOwner:name:color:width:height:scale:complete:)
|
|
14
|
+
static func request(
|
|
15
|
+
owner: AnyObject,
|
|
16
|
+
name: String,
|
|
17
|
+
color: String,
|
|
18
|
+
width: Int,
|
|
19
|
+
height: Int,
|
|
20
|
+
scale: Double,
|
|
21
|
+
complete: @escaping (UIImage?) -> Void
|
|
22
|
+
) {
|
|
23
|
+
OneKeyNamedSVG.shared.request(
|
|
24
|
+
owner: owner,
|
|
25
|
+
name: name,
|
|
26
|
+
color: color,
|
|
27
|
+
width: width,
|
|
28
|
+
height: height,
|
|
29
|
+
scale: CGFloat(scale),
|
|
30
|
+
complete: complete
|
|
31
|
+
)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// Process-owned resource metadata and immutable raster cache, independent of JS runtimes.
|
|
36
|
+
public final class OneKeyNamedSVG {
|
|
37
|
+
public static let shared = OneKeyNamedSVG()
|
|
38
|
+
private init() {}
|
|
39
|
+
public enum RecolorMode: String { case fixed, single, multiple, raster }
|
|
40
|
+
public struct IconMetadata {
|
|
41
|
+
public let width: Double
|
|
42
|
+
public let height: Double
|
|
43
|
+
public let recolorMode: RecolorMode
|
|
44
|
+
|
|
45
|
+
public init(width: Double, height: Double, recolorMode: RecolorMode) {
|
|
46
|
+
self.width = width
|
|
47
|
+
self.height = height
|
|
48
|
+
self.recolorMode = recolorMode
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
public struct RenderResult {
|
|
52
|
+
public let image: UIImage
|
|
53
|
+
public let mode: RecolorMode
|
|
54
|
+
public let sourceIdentity: String
|
|
55
|
+
public let maskAlpha: CGFloat
|
|
56
|
+
|
|
57
|
+
public func canTint(_ color: String) -> Bool {
|
|
58
|
+
guard let value = OneKeyNamedSVG.channels(color) else { return false }
|
|
59
|
+
return mode == .fixed || mode == .single || (mode == .multiple && value[3] == maskAlpha)
|
|
60
|
+
}
|
|
61
|
+
public func tintColor(_ color: String) -> UIColor? {
|
|
62
|
+
guard mode == .single || mode == .multiple, let value = OneKeyNamedSVG.channels(color) else { return nil }
|
|
63
|
+
return UIColor(red: value[0], green: value[1], blue: value[2], alpha: mode == .single ? value[3] : 1)
|
|
64
|
+
}
|
|
65
|
+
fileprivate func finalImage(_ color: String) -> UIImage {
|
|
66
|
+
guard let tint = tintColor(color) else { return image }
|
|
67
|
+
if OneKeyNamedSVG.channels(color) == [0, 0, 0, 1] { return image }
|
|
68
|
+
// UIImage tint wrappers can retain the original black cgImage. Legacy callers
|
|
69
|
+
// receive actual final-color pixels, so bake the wrapper on the worker.
|
|
70
|
+
let format = UIGraphicsImageRendererFormat(); format.scale = 1; format.preferredRange = .standard
|
|
71
|
+
return UIGraphicsImageRenderer(size: image.size, format: format).image { _ in
|
|
72
|
+
image.withTintColor(tint, renderingMode: .alwaysOriginal).draw(in: CGRect(origin: .zero, size: image.size))
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
private static func channels(_ color: String) -> [CGFloat]? {
|
|
78
|
+
guard color.range(of: #"^rgba\(\d{1,3},\d{1,3},\d{1,3},(?:0(?:\.\d+)?|1(?:\.0+)?)\)$"#, options: .regularExpression) != nil else { return nil }
|
|
79
|
+
let parts = color.dropFirst(5).dropLast().split(separator: ",").compactMap { Double($0) }
|
|
80
|
+
guard parts.count == 4, parts.prefix(3).allSatisfy({ (0...255).contains($0) }), (0...1).contains(parts[3]) else { return nil }
|
|
81
|
+
return parts.enumerated().map { CGFloat($0.offset == 3 ? $0.element : $0.element / 255) }
|
|
82
|
+
}
|
|
83
|
+
public static func isValidColor(_ color: String) -> Bool { channels(color) != nil }
|
|
84
|
+
|
|
85
|
+
private struct Request {
|
|
86
|
+
let name: String
|
|
87
|
+
let color: String
|
|
88
|
+
let width: Int
|
|
89
|
+
let height: Int
|
|
90
|
+
let scale: CGFloat
|
|
91
|
+
let finalColor: Bool
|
|
92
|
+
let complete: (RenderResult?) -> Void
|
|
93
|
+
}
|
|
94
|
+
private let lock = NSLock()
|
|
95
|
+
private let metadataLock = NSLock()
|
|
96
|
+
private var pending: [ObjectIdentifier: Request] = [:]
|
|
97
|
+
private var order: [ObjectIdentifier] = []
|
|
98
|
+
private var workers = 0
|
|
99
|
+
private var metadata: [String: [String: Any]]?
|
|
100
|
+
private var resourceBundle: Bundle?
|
|
101
|
+
private var cache: [String: RenderResult] = [:]
|
|
102
|
+
private var recency: [String] = []
|
|
103
|
+
private var bytes = 0
|
|
104
|
+
|
|
105
|
+
public func cancel(owner: AnyObject) {
|
|
106
|
+
lock.lock(); defer { lock.unlock() }
|
|
107
|
+
let key = ObjectIdentifier(owner)
|
|
108
|
+
pending.removeValue(forKey: key)
|
|
109
|
+
order.removeAll { $0 == key }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
private func loadManifestIfNeeded() {
|
|
113
|
+
guard metadata == nil else { return }
|
|
114
|
+
let owner = Bundle(for: OneKeyIconBundleToken.self)
|
|
115
|
+
let url = owner.url(forResource: "OneKeyIcons", withExtension: "bundle")
|
|
116
|
+
?? Bundle.main.url(forResource: "OneKeyIcons", withExtension: "bundle")
|
|
117
|
+
resourceBundle = url.flatMap(Bundle.init(url:))
|
|
118
|
+
if let file = resourceBundle?.url(forResource: "manifest", withExtension: "json"),
|
|
119
|
+
let data = try? Data(contentsOf: file) {
|
|
120
|
+
metadata = (try? JSONSerialization.jsonObject(with: data)) as? [String: [String: Any]]
|
|
121
|
+
}
|
|
122
|
+
if metadata == nil {
|
|
123
|
+
// Hosts own the resources; a missing bundle means every named icon stays blank.
|
|
124
|
+
NSLog("[OneKeyIcon] OneKeyIcons.bundle/manifest.json is missing or invalid; named icons will not render")
|
|
125
|
+
metadata = [:]
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
private static func renderKey(name: String, digest: String, width: Int, height: Int,
|
|
130
|
+
scale: CGFloat, mode: RecolorMode, color: String,
|
|
131
|
+
channels: [CGFloat]) -> (identity: String, key: String, maskAlpha: CGFloat) {
|
|
132
|
+
let identity = "\(name)|\(digest)|\(width)|\(height)|\(scale)"
|
|
133
|
+
let maskAlpha: CGFloat = mode == .multiple ? channels[3] : 1
|
|
134
|
+
let key = "\(identity)|\(mode.rawValue)|\(mode == .raster ? color : mode == .multiple ? String(Double(maskAlpha)) : "")"
|
|
135
|
+
return (identity, key, maskAlpha)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/// Main-thread fast path: returns an already-decoded result without disk I/O or
|
|
139
|
+
/// manifest loading, so remounted and recycled views paint in the same frame.
|
|
140
|
+
public func cachedRender(name: String, color: String, width: Int, height: Int,
|
|
141
|
+
scale: CGFloat) -> RenderResult? {
|
|
142
|
+
guard let channels = Self.channels(color), metadataLock.try() else { return nil }
|
|
143
|
+
let entry = metadata?[name]
|
|
144
|
+
metadataLock.unlock()
|
|
145
|
+
guard let digest = entry?["digest"] as? String else { return nil }
|
|
146
|
+
let mode = (entry?["recolorMode"] as? String).flatMap(RecolorMode.init(rawValue:)) ?? .raster
|
|
147
|
+
let key = Self.renderKey(name: name, digest: digest, width: width, height: height, scale: scale,
|
|
148
|
+
mode: mode, color: color, channels: channels).key
|
|
149
|
+
lock.lock(); defer { lock.unlock() }
|
|
150
|
+
guard let hit = cache[key] else { return nil }
|
|
151
|
+
recency.removeAll { $0 == key }; recency.append(key)
|
|
152
|
+
return hit
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
public func iconMetadata(forName name: String) -> IconMetadata? {
|
|
156
|
+
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
157
|
+
guard !trimmed.isEmpty else { return nil }
|
|
158
|
+
metadataLock.lock()
|
|
159
|
+
loadManifestIfNeeded()
|
|
160
|
+
let entry = metadata?[trimmed]
|
|
161
|
+
metadataLock.unlock()
|
|
162
|
+
guard let entry else { return nil }
|
|
163
|
+
let mode = (entry["recolorMode"] as? String).flatMap(RecolorMode.init(rawValue:)) ?? .raster
|
|
164
|
+
let width: Double
|
|
165
|
+
let height: Double
|
|
166
|
+
if let vb = entry["viewBox"] as? [NSNumber], vb.count >= 4 {
|
|
167
|
+
let vbWidth = vb[2].doubleValue
|
|
168
|
+
let vbHeight = vb[3].doubleValue
|
|
169
|
+
width = (vbWidth > 0 && vbHeight > 0) ? vbWidth : 24
|
|
170
|
+
height = (vbWidth > 0 && vbHeight > 0) ? vbHeight : 24
|
|
171
|
+
} else {
|
|
172
|
+
width = 24
|
|
173
|
+
height = 24
|
|
174
|
+
}
|
|
175
|
+
return IconMetadata(width: width, height: height, recolorMode: mode)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
public func request(owner: AnyObject, name: String, color: String, width: Int,
|
|
179
|
+
height: Int, scale: CGFloat, complete: @escaping (UIImage?) -> Void) {
|
|
180
|
+
enqueue(owner: owner, name: name, color: color, width: width, height: height, scale: scale,
|
|
181
|
+
finalColor: true) { complete($0?.image) }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
public func requestRender(owner: AnyObject, name: String, color: String, width: Int,
|
|
185
|
+
height: Int, scale: CGFloat, complete: @escaping (RenderResult?) -> Void) {
|
|
186
|
+
enqueue(owner: owner, name: name, color: color, width: width, height: height, scale: scale,
|
|
187
|
+
finalColor: false, complete: complete)
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
private func enqueue(owner: AnyObject, name: String, color: String, width: Int,
|
|
191
|
+
height: Int, scale: CGFloat, finalColor: Bool, complete: @escaping (RenderResult?) -> Void) {
|
|
192
|
+
lock.lock(); defer { lock.unlock() }
|
|
193
|
+
let key = ObjectIdentifier(owner)
|
|
194
|
+
if pending[key] == nil { order.append(key) }
|
|
195
|
+
pending[key] = Request(name: name, color: color, width: width, height: height, scale: scale,
|
|
196
|
+
finalColor: finalColor, complete: complete)
|
|
197
|
+
while workers < 2 && workers < pending.count {
|
|
198
|
+
workers += 1
|
|
199
|
+
DispatchQueue.global(qos: .userInitiated).async { self.drain() }
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
private func drain() {
|
|
204
|
+
while true {
|
|
205
|
+
lock.lock()
|
|
206
|
+
guard !order.isEmpty, let request = pending.removeValue(forKey: order.removeFirst()) else {
|
|
207
|
+
workers -= 1; lock.unlock(); return
|
|
208
|
+
}
|
|
209
|
+
lock.unlock()
|
|
210
|
+
let image = autoreleasepool { () -> RenderResult? in
|
|
211
|
+
guard let result = decode(request) else { return nil }
|
|
212
|
+
if !request.finalColor { return result }
|
|
213
|
+
return RenderResult(image: result.finalImage(request.color), mode: .raster,
|
|
214
|
+
sourceIdentity: result.sourceIdentity, maskAlpha: result.maskAlpha)
|
|
215
|
+
}
|
|
216
|
+
DispatchQueue.main.async { request.complete(image) }
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
private func decode(_ request: Request) -> RenderResult? {
|
|
221
|
+
guard (1...4096).contains(request.width), (1...4096).contains(request.height),
|
|
222
|
+
request.width * request.height <= 4_194_304, request.scale.isFinite,
|
|
223
|
+
request.scale > 0,
|
|
224
|
+
let channels = Self.channels(request.color) else { return nil }
|
|
225
|
+
metadataLock.lock()
|
|
226
|
+
loadManifestIfNeeded()
|
|
227
|
+
let entry = metadata?[request.name]
|
|
228
|
+
let bundle = resourceBundle
|
|
229
|
+
metadataLock.unlock()
|
|
230
|
+
guard let digest = entry?["digest"] as? String,
|
|
231
|
+
let url = bundle?.url(forResource: request.name, withExtension: "svg") else { return nil }
|
|
232
|
+
let mode = (entry?["recolorMode"] as? String).flatMap(RecolorMode.init(rawValue:)) ?? .raster
|
|
233
|
+
let (sourceIdentity, key, maskAlpha) = Self.renderKey(
|
|
234
|
+
name: request.name, digest: digest, width: request.width, height: request.height,
|
|
235
|
+
scale: request.scale, mode: mode, color: request.color, channels: channels)
|
|
236
|
+
let paintColor: String
|
|
237
|
+
switch mode {
|
|
238
|
+
case .fixed, .single: paintColor = "rgba(0,0,0,1)"
|
|
239
|
+
case .multiple: paintColor = "rgba(0,0,0,\(maskAlpha))"
|
|
240
|
+
case .raster: paintColor = request.color
|
|
241
|
+
}
|
|
242
|
+
lock.lock()
|
|
243
|
+
if let image = cache[key] {
|
|
244
|
+
recency.removeAll { $0 == key }; recency.append(key)
|
|
245
|
+
lock.unlock(); return image
|
|
246
|
+
}
|
|
247
|
+
lock.unlock()
|
|
248
|
+
guard let source = try? String(contentsOf: url, encoding: .utf8),
|
|
249
|
+
let pattern = try? NSRegularExpression(pattern: #"((?:fill|stroke)\s*=\s*["'])currentColor(["'])"#) else { return nil }
|
|
250
|
+
// CoreSVG interprets integer rgba alpha as an 8-bit channel; decimals retain CSS endpoints.
|
|
251
|
+
let svgColor = paintColor.replacingOccurrences(of: #",(0|1)\)$"#, with: ",$1.0)", options: .regularExpression)
|
|
252
|
+
let xml = pattern.stringByReplacingMatches(in: source, range: NSRange(source.startIndex..., in: source),
|
|
253
|
+
withTemplate: "$1\(svgColor)$2")
|
|
254
|
+
guard let data = xml.data(using: .utf8),
|
|
255
|
+
let image = OneKeyImageCoderBridge.decodeSVG(data, pixelSize: CGSize(width: request.width, height: request.height)),
|
|
256
|
+
image.size.width > 0, image.size.height > 0 else { return nil }
|
|
257
|
+
let size = CGSize(width: request.width, height: request.height)
|
|
258
|
+
let format = UIGraphicsImageRendererFormat()
|
|
259
|
+
format.scale = 1
|
|
260
|
+
format.preferredRange = .standard
|
|
261
|
+
let output = UIGraphicsImageRenderer(size: size, format: format).image { _ in
|
|
262
|
+
let ratio = min(size.width / image.size.width, size.height / image.size.height)
|
|
263
|
+
let fitted = CGSize(width: image.size.width * ratio, height: image.size.height * ratio)
|
|
264
|
+
image.draw(in: CGRect(x: (size.width - fitted.width) / 2, y: (size.height - fitted.height) / 2,
|
|
265
|
+
width: fitted.width, height: fitted.height))
|
|
266
|
+
}
|
|
267
|
+
let result = RenderResult(image: output, mode: mode, sourceIdentity: sourceIdentity, maskAlpha: maskAlpha)
|
|
268
|
+
let cost = (output.cgImage?.bytesPerRow ?? request.width * 4) * request.height
|
|
269
|
+
if cost <= 8_388_608 {
|
|
270
|
+
lock.lock(); defer { lock.unlock() }
|
|
271
|
+
if let previous = cache[key] { bytes -= (previous.image.cgImage?.bytesPerRow ?? request.width * 4) * request.height }
|
|
272
|
+
cache[key] = result
|
|
273
|
+
recency.removeAll { $0 == key }; recency.append(key)
|
|
274
|
+
bytes += cost
|
|
275
|
+
while cache.count > 128 || bytes > 8_388_608 {
|
|
276
|
+
let oldest = recency.removeFirst()
|
|
277
|
+
if let image = cache.removeValue(forKey: oldest) { bytes -= (image.image.cgImage?.bytesPerRow ?? 0) * (image.image.cgImage?.height ?? 0) }
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return result
|
|
281
|
+
}
|
|
282
|
+
}
|