@onekeyfe/react-native-image 6.7.0-alpha.466 → 6.8.0-10

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.
Files changed (34) hide show
  1. package/README.md +144 -86
  2. package/android/build.gradle +1 -0
  3. package/android/consumer-rules.pro +9 -0
  4. package/android/src/main/AndroidManifest.xml +12 -1
  5. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyBlockieAvatarLoader.kt +1 -1
  6. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyIcon.kt +5 -1
  7. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImage.kt +240 -6
  8. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageCache.kt +16 -0
  9. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageGlideModule.kt +17 -0
  10. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageGlideRegistry.kt +19 -0
  11. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageSafety.kt +41 -0
  12. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageStartupPrewarm.kt +1106 -0
  13. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageStartupProvider.kt +54 -0
  14. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyMainThreadDecode.kt +541 -0
  15. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyMediaPreviewCache.kt +199 -0
  16. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyNamedSVG.kt +758 -61
  17. package/android/src/test/java/com/margelo/nitro/onekeyimage/OneKeyBlockieAvatarLoaderTest.kt +2 -1
  18. package/android/src/test/java/com/margelo/nitro/onekeyimage/OneKeyStartupPrewarmTest.kt +600 -0
  19. package/ios/OneKeyAvatarImageLoader.swift +1 -1
  20. package/ios/OneKeyIcon.swift +6 -0
  21. package/ios/OneKeyImage.swift +85 -2
  22. package/ios/OneKeyImageCache.swift +25 -5
  23. package/ios/OneKeyImageCoderBridge.m +42 -1
  24. package/ios/OneKeyImageRequestContext.swift +16 -2
  25. package/ios/OneKeyImageStartupPrewarm.swift +602 -0
  26. package/ios/OneKeyMainThreadDecode.swift +338 -0
  27. package/ios/OneKeyMediaPreviewCache.swift +209 -0
  28. package/ios/OneKeyNamedSVG.swift +437 -9
  29. package/ios/tests/OneKeyIconTests.swift +238 -0
  30. package/ios/tests/OneKeyImageInfrastructureTests.swift +611 -0
  31. package/ios/tests/OneKeyMediaPreviewCacheTests.swift +139 -0
  32. package/lib/module/index.js +5 -1
  33. package/package.json +1 -1
  34. package/src/index.tsx +23 -2
@@ -1,4 +1,6 @@
1
1
  import Foundation
2
+ import QuartzCore
3
+ import SDWebImage
2
4
  import UIKit
3
5
 
4
6
  private final class OneKeyIconBundleToken: NSObject {}
@@ -30,6 +32,12 @@ internal final class OneKeyNamedSVGBridge: NSObject {
30
32
  complete: complete
31
33
  )
32
34
  }
35
+
36
+ /// Called off the main thread at process start; see `OneKeyNamedSVGStartupLoader`.
37
+ @objc(prewarmStartupSet)
38
+ static func prewarmStartupSet() {
39
+ OneKeyNamedSVG.shared.prewarmStartupSet()
40
+ }
33
41
  }
34
42
 
35
43
  /// Process-owned resource metadata and immutable raster cache, independent of JS runtimes.
@@ -91,6 +99,22 @@ public final class OneKeyNamedSVG {
91
99
  let finalColor: Bool
92
100
  let complete: (RenderResult?) -> Void
93
101
  }
102
+ private static let rasterDiskCache: SDImageCache = {
103
+ let config = SDImageCacheConfig()
104
+ config.shouldCacheImagesInMemory = false
105
+ config.shouldUseWeakMemoryCache = false
106
+ // Source digests invalidate changed assets; retain only size-based eviction.
107
+ config.maxDiskAge = -1
108
+ config.maxDiskSize = 128 * 1024 * 1024
109
+ config.diskCacheWritingOptions = .atomic
110
+ return SDImageCache(namespace: "onekey-named-svg-raster-v1", diskCacheDirectory: nil, config: config)
111
+ }()
112
+ private static let diskWriter = DispatchQueue(label: "onekey.svg.raster-disk", qos: .utility)
113
+
114
+ var rasterDiskCacheForTesting: SDImageCache {
115
+ Self.rasterDiskCache
116
+ }
117
+
94
118
  private let lock = NSLock()
95
119
  private let metadataLock = NSLock()
96
120
  private var pending: [ObjectIdentifier: Request] = [:]
@@ -102,6 +126,305 @@ public final class OneKeyNamedSVG {
102
126
  private var recency: [String] = []
103
127
  private var bytes = 0
104
128
 
129
+ // MARK: Startup prewarm
130
+ //
131
+ // A cold process starts with an empty memory cache, so every icon of the first
132
+ // screen would miss `cachedRender` and paint one frame late. The requests seen
133
+ // right after launch are persisted and decoded again on a background queue at
134
+ // the next process start, before JS mounts the first screen.
135
+
136
+ struct StartupIdentity: Hashable {
137
+ let name: String
138
+ let color: String
139
+ let width: Int
140
+ let height: Int
141
+ let scale: Double
142
+ }
143
+
144
+ struct StartupEntry: Codable, Equatable {
145
+ let name: String
146
+ let color: String
147
+ let width: Int
148
+ let height: Int
149
+ let scale: Double
150
+ var launch: Int
151
+
152
+ var identity: StartupIdentity {
153
+ StartupIdentity(name: name, color: color, width: width, height: height, scale: scale)
154
+ }
155
+
156
+ private enum CodingKeys: String, CodingKey {
157
+ case name
158
+ case color
159
+ case width
160
+ case height
161
+ case scale
162
+ case launch
163
+ }
164
+
165
+ init(name: String, color: String, width: Int, height: Int, scale: Double, launch: Int = 0) {
166
+ self.name = name
167
+ self.color = color
168
+ self.width = width
169
+ self.height = height
170
+ self.scale = scale
171
+ self.launch = launch
172
+ }
173
+
174
+ init(from decoder: Decoder) throws {
175
+ let container = try decoder.container(keyedBy: CodingKeys.self)
176
+ self.name = try container.decode(String.self, forKey: .name)
177
+ self.color = try container.decode(String.self, forKey: .color)
178
+ self.width = try container.decode(Int.self, forKey: .width)
179
+ self.height = try container.decode(Int.self, forKey: .height)
180
+ self.scale = try container.decode(Double.self, forKey: .scale)
181
+ self.launch = try container.decodeIfPresent(Int.self, forKey: .launch) ?? 0
182
+ }
183
+
184
+ func encode(to encoder: Encoder) throws {
185
+ var container = encoder.container(keyedBy: CodingKeys.self)
186
+ try container.encode(name, forKey: .name)
187
+ try container.encode(color, forKey: .color)
188
+ try container.encode(width, forKey: .width)
189
+ try container.encode(height, forKey: .height)
190
+ try container.encode(scale, forKey: .scale)
191
+ if launch > 0 {
192
+ try container.encode(launch, forKey: .launch)
193
+ }
194
+ }
195
+ }
196
+
197
+ struct StartupMetrics: Equatable {
198
+ var entryCount: Int = 0
199
+ var decodedCount: Int = 0
200
+ var manifestLoadMs: Double = 0
201
+ var totalMs: Double = 0
202
+ }
203
+
204
+ static let startupWindow: TimeInterval = 6
205
+ static let startupMaxDuration: TimeInterval = 60
206
+ static let startupMinimumSettledCount = 8
207
+ static let startupLimit = 96
208
+ static let startupMaxLaunchAge = 3
209
+ private static let startupFile: URL? = FileManager.default
210
+ .urls(for: .cachesDirectory, in: .userDomainMask).first?
211
+ .appendingPathComponent("onekey-named-svg-startup-v1.json")
212
+ private let startupLock = NSLock()
213
+ private var startupSeen: [StartupEntry] = []
214
+ private var startupPrevious: [StartupEntry] = []
215
+ private var startupMaxLaunch = 0
216
+ private var startupLoadedPreviousFromDisk = false
217
+ private var startupRecording: Bool?
218
+ private var startupFirstRequestAt: CFTimeInterval = 0
219
+ private var startupFlushWorkItem: DispatchWorkItem?
220
+ private var customStartupFile: URL?
221
+ private var startupMetrics = StartupMetrics()
222
+
223
+ private var activeStartupFileURL: URL? {
224
+ customStartupFile ?? Self.startupFile
225
+ }
226
+
227
+ func prewarmStartupSet() {
228
+ let start = CACurrentMediaTime()
229
+ // The manifest is needed by every main-thread fast path, with or without a list.
230
+ metadataLock.lock()
231
+ loadManifestIfNeeded()
232
+ metadataLock.unlock()
233
+ let manifestMs = (CACurrentMediaTime() - start) * 1000.0
234
+ startupLock.lock()
235
+ let file = activeStartupFileURL
236
+ startupLock.unlock()
237
+ guard let file, let data = try? Data(contentsOf: file),
238
+ let entries = try? JSONDecoder().decode([StartupEntry].self, from: data) else {
239
+ startupLock.lock()
240
+ startupMetrics = StartupMetrics(
241
+ entryCount: 0,
242
+ decodedCount: 0,
243
+ manifestLoadMs: manifestMs,
244
+ totalMs: manifestMs
245
+ )
246
+ startupLock.unlock()
247
+ return
248
+ }
249
+ let highestLaunch = entries.map(\.launch).max() ?? 0
250
+ startupLock.lock()
251
+ startupLoadedPreviousFromDisk = true
252
+ if startupPrevious.isEmpty {
253
+ startupPrevious = entries
254
+ startupMaxLaunch = max(startupMaxLaunch, highestLaunch)
255
+ }
256
+ startupLock.unlock()
257
+ var decodedCount = 0
258
+ let bounded = entries.prefix(Self.startupLimit)
259
+ for entry in bounded {
260
+ autoreleasepool {
261
+ if decode(Request(name: entry.name, color: entry.color, width: entry.width,
262
+ height: entry.height, scale: CGFloat(entry.scale), finalColor: false, complete: { _ in })) != nil {
263
+ decodedCount += 1
264
+ }
265
+ }
266
+ }
267
+ let totalMs = (CACurrentMediaTime() - start) * 1000.0
268
+ startupLock.lock()
269
+ startupMetrics = StartupMetrics(
270
+ entryCount: bounded.count,
271
+ decodedCount: decodedCount,
272
+ manifestLoadMs: manifestMs,
273
+ totalMs: totalMs
274
+ )
275
+ startupLock.unlock()
276
+ NSLog(
277
+ "[OneKeyImageStartupMetrics] iconPrewarm entries=%d decoded=%d manifestMs=%.3f totalMs=%.3f",
278
+ bounded.count,
279
+ decodedCount,
280
+ manifestMs,
281
+ totalMs
282
+ )
283
+ }
284
+
285
+ private func noteStartupRequest(name: String, color: String, width: Int, height: Int, scale: CGFloat) {
286
+ guard (1...4096).contains(width), (1...4096).contains(height),
287
+ scale.isFinite, scale > 0, Self.isValidColor(color) else { return }
288
+ let identity = StartupIdentity(name: name, color: color, width: width, height: height, scale: Double(scale))
289
+ startupLock.lock()
290
+ defer { startupLock.unlock() }
291
+ if startupRecording == false { return }
292
+ let now = CACurrentMediaTime()
293
+ if startupRecording == nil {
294
+ startupRecording = true
295
+ startupFirstRequestAt = now
296
+ }
297
+ guard startupSeen.count < Self.startupLimit,
298
+ !startupSeen.contains(where: { $0.identity == identity }) else { return }
299
+ startupSeen.append(
300
+ StartupEntry(name: name, color: color, width: width, height: height, scale: Double(scale), launch: 0)
301
+ )
302
+ startupFlushWorkItem?.cancel()
303
+ let item = DispatchWorkItem { [weak self] in
304
+ self?.persistStartupSet(forceClose: false)
305
+ }
306
+ startupFlushWorkItem = item
307
+ Self.diskWriter.asyncAfter(deadline: .now() + Self.startupWindow, execute: item)
308
+ }
309
+
310
+ private func persistStartupSet(forceClose: Bool) {
311
+ startupLock.lock()
312
+ guard startupRecording == true else {
313
+ startupLock.unlock()
314
+ return
315
+ }
316
+ let file = activeStartupFileURL
317
+ if !startupLoadedPreviousFromDisk {
318
+ startupLoadedPreviousFromDisk = true
319
+ if startupPrevious.isEmpty,
320
+ let file,
321
+ let data = try? Data(contentsOf: file),
322
+ let loaded = try? JSONDecoder().decode([StartupEntry].self, from: data) {
323
+ startupPrevious = loaded
324
+ startupMaxLaunch = max(startupMaxLaunch, loaded.map(\.launch).max() ?? 0)
325
+ }
326
+ }
327
+ let elapsed = CACurrentMediaTime() - startupFirstRequestAt
328
+ let shouldClose =
329
+ forceClose
330
+ || startupSeen.count >= Self.startupMinimumSettledCount
331
+ || startupSeen.count >= Self.startupLimit
332
+ || elapsed >= Self.startupMaxDuration
333
+
334
+ let seenIdentities = Set(startupSeen.map(\.identity))
335
+ let previousIdentities = startupPrevious.map(\.identity)
336
+ let currentIdentities = startupSeen.map(\.identity)
337
+ let allPreviousAtMaxLaunch = startupPrevious.allSatisfy { $0.launch == startupMaxLaunch }
338
+ let steadyStateUnchanged =
339
+ !startupPrevious.isEmpty
340
+ && currentIdentities == previousIdentities
341
+ && allPreviousAtMaxLaunch
342
+
343
+ let nextLaunch = steadyStateUnchanged ? startupMaxLaunch : (startupMaxLaunch + 1)
344
+ let currentStamped = startupSeen.map { entry -> StartupEntry in
345
+ var copy = entry
346
+ copy.launch = nextLaunch
347
+ return copy
348
+ }
349
+ // This launch's first screen leads; recent earlier entries stay warm until aged out.
350
+ let retainedPrevious = startupPrevious.filter { entry in
351
+ !seenIdentities.contains(entry.identity) && (nextLaunch - entry.launch) < Self.startupMaxLaunchAge
352
+ }
353
+ let merged = Array((currentStamped + retainedPrevious).prefix(Self.startupLimit))
354
+
355
+ if shouldClose {
356
+ startupRecording = false
357
+ startupFlushWorkItem = nil
358
+ startupSeen = []
359
+ startupPrevious = merged
360
+ startupMaxLaunch = nextLaunch
361
+ }
362
+ startupLock.unlock()
363
+
364
+ guard !steadyStateUnchanged, let file,
365
+ let data = try? JSONEncoder().encode(merged) else { return }
366
+ try? data.write(to: file, options: .atomic)
367
+ }
368
+
369
+ func startupMetricsSnapshot() -> StartupMetrics {
370
+ startupLock.lock()
371
+ defer { startupLock.unlock() }
372
+ return startupMetrics
373
+ }
374
+
375
+ func flushStartupForTesting(forceClose: Bool = true) {
376
+ Self.diskWriter.sync {
377
+ self.startupLock.lock()
378
+ self.startupFlushWorkItem?.cancel()
379
+ self.startupFlushWorkItem = nil
380
+ self.startupLock.unlock()
381
+ self.persistStartupSet(forceClose: forceClose)
382
+ }
383
+ }
384
+
385
+ func resetStartupForTesting(fileURL: URL? = nil, keepPreviousFromDisk: Bool = false) {
386
+ Self.diskWriter.sync {
387
+ self.startupLock.lock()
388
+ self.startupFlushWorkItem?.cancel()
389
+ self.startupFlushWorkItem = nil
390
+ self.startupSeen = []
391
+ if !keepPreviousFromDisk {
392
+ self.startupPrevious = []
393
+ self.startupMaxLaunch = 0
394
+ self.startupLoadedPreviousFromDisk = false
395
+ }
396
+ self.startupRecording = nil
397
+ self.startupFirstRequestAt = 0
398
+ self.customStartupFile = fileURL
399
+ self.startupMetrics = StartupMetrics()
400
+ self.startupLock.unlock()
401
+ }
402
+ }
403
+
404
+ func clearMemoryCacheForTesting() {
405
+ lock.lock()
406
+ cache.removeAll()
407
+ recency.removeAll()
408
+ bytes = 0
409
+ lock.unlock()
410
+ }
411
+
412
+ func rasterDiskCachePathForTesting(name: String, color: String, width: Int,
413
+ height: Int, scale: CGFloat) -> String? {
414
+ guard let channels = Self.channels(color) else { return nil }
415
+ metadataLock.lock()
416
+ loadManifestIfNeeded()
417
+ let entry = metadata?[name]
418
+ metadataLock.unlock()
419
+ guard let digest = entry?["digest"] as? String else { return nil }
420
+ let mode = (entry?["recolorMode"] as? String).flatMap(RecolorMode.init(rawValue:)) ?? .raster
421
+ let key = Self.renderKey(
422
+ name: name, digest: digest, width: width, height: height,
423
+ scale: scale, mode: mode, color: color, channels: channels
424
+ ).key
425
+ return Self.rasterDiskCache.cachePath(forKey: key)
426
+ }
427
+
105
428
  public func cancel(owner: AnyObject) {
106
429
  lock.lock(); defer { lock.unlock() }
107
430
  let key = ObjectIdentifier(owner)
@@ -139,6 +462,7 @@ public final class OneKeyNamedSVG {
139
462
  /// manifest loading, so remounted and recycled views paint in the same frame.
140
463
  public func cachedRender(name: String, color: String, width: Int, height: Int,
141
464
  scale: CGFloat) -> RenderResult? {
465
+ noteStartupRequest(name: name, color: color, width: width, height: height, scale: scale)
142
466
  guard let channels = Self.channels(color), metadataLock.try() else { return nil }
143
467
  let entry = metadata?[name]
144
468
  metadataLock.unlock()
@@ -177,12 +501,32 @@ public final class OneKeyNamedSVG {
177
501
 
178
502
  public func request(owner: AnyObject, name: String, color: String, width: Int,
179
503
  height: Int, scale: CGFloat, complete: @escaping (UIImage?) -> Void) {
504
+ if Thread.isMainThread {
505
+ if let hit = cachedRender(name: name, color: color, width: width, height: height, scale: scale)
506
+ ?? diskRender(name: name, color: color, width: width, height: height, scale: scale) {
507
+ cancel(owner: owner)
508
+ complete(hit.finalImage(color))
509
+ return
510
+ }
511
+ } else {
512
+ noteStartupRequest(name: name, color: color, width: width, height: height, scale: scale)
513
+ }
180
514
  enqueue(owner: owner, name: name, color: color, width: width, height: height, scale: scale,
181
515
  finalColor: true) { complete($0?.image) }
182
516
  }
183
517
 
184
518
  public func requestRender(owner: AnyObject, name: String, color: String, width: Int,
185
519
  height: Int, scale: CGFloat, complete: @escaping (RenderResult?) -> Void) {
520
+ if Thread.isMainThread {
521
+ if let hit = cachedRender(name: name, color: color, width: width, height: height, scale: scale)
522
+ ?? diskRender(name: name, color: color, width: width, height: height, scale: scale) {
523
+ cancel(owner: owner)
524
+ complete(hit)
525
+ return
526
+ }
527
+ } else {
528
+ noteStartupRequest(name: name, color: color, width: width, height: height, scale: scale)
529
+ }
186
530
  enqueue(owner: owner, name: name, color: color, width: width, height: height, scale: scale,
187
531
  finalColor: false, complete: complete)
188
532
  }
@@ -217,18 +561,46 @@ public final class OneKeyNamedSVG {
217
561
  }
218
562
  }
219
563
 
220
- private func decode(_ request: Request) -> RenderResult? {
564
+ /// Main-thread path for a memory miss: a small icon (<= 192px edge and <= 32 KiB
565
+ /// encoded raster on disk) is read and bound in the same frame. It never parses
566
+ /// SVG, loads the manifest or waits for a lock; any of those leaves the miss to workers.
567
+ public func diskRender(name: String, color: String, width: Int, height: Int,
568
+ scale: CGFloat) -> RenderResult? {
569
+ guard width > 0, height > 0,
570
+ width <= OneKeyMainThreadDecode.maximumIconEdge,
571
+ height <= OneKeyMainThreadDecode.maximumIconEdge else { return nil }
572
+ return OneKeyMainThreadDecode.run {
573
+ decode(Request(name: name, color: color, width: width, height: height, scale: scale,
574
+ finalColor: false, complete: { _ in }), diskOnly: true)
575
+ }
576
+ }
577
+
578
+ private func decode(_ request: Request, diskOnly: Bool = false) -> RenderResult? {
221
579
  guard (1...4096).contains(request.width), (1...4096).contains(request.height),
222
580
  request.width * request.height <= 4_194_304, request.scale.isFinite,
223
581
  request.scale > 0,
224
582
  let channels = Self.channels(request.color) else { return nil }
225
- metadataLock.lock()
226
- loadManifestIfNeeded()
583
+ if diskOnly {
584
+ guard metadataLock.try() else {
585
+ OneKeyMainThreadDecode.noteLockContention()
586
+ return nil
587
+ }
588
+ guard metadata != nil else {
589
+ metadataLock.unlock()
590
+ OneKeyMainThreadDecode.noteDiskMiss()
591
+ return nil
592
+ }
593
+ } else {
594
+ metadataLock.lock()
595
+ loadManifestIfNeeded()
596
+ }
227
597
  let entry = metadata?[request.name]
228
598
  let bundle = resourceBundle
229
599
  metadataLock.unlock()
230
- guard let digest = entry?["digest"] as? String,
231
- let url = bundle?.url(forResource: request.name, withExtension: "svg") else { return nil }
600
+ guard let digest = entry?["digest"] as? String else {
601
+ if diskOnly { OneKeyMainThreadDecode.noteDiskMiss() }
602
+ return nil
603
+ }
232
604
  let mode = (entry?["recolorMode"] as? String).flatMap(RecolorMode.init(rawValue:)) ?? .raster
233
605
  let (sourceIdentity, key, maskAlpha) = Self.renderKey(
234
606
  name: request.name, digest: digest, width: request.width, height: request.height,
@@ -245,7 +617,52 @@ public final class OneKeyNamedSVG {
245
617
  lock.unlock(); return image
246
618
  }
247
619
  lock.unlock()
248
- guard let source = try? String(contentsOf: url, encoding: .utf8),
620
+ // The source digest and all raster inputs are in the key; diskOnly bounds encoded byte size
621
+ // and reads directly from disk to avoid blocking on SDImageCache's shared ioQueue.
622
+ let diskCache = Self.rasterDiskCache
623
+ let diskImage: UIImage?
624
+ if diskOnly {
625
+ guard let path = diskCache.cachePath(forKey: key),
626
+ let attributes = try? FileManager.default.attributesOfItem(atPath: path),
627
+ let size = (attributes[.size] as? NSNumber)?.intValue,
628
+ size > 0 else {
629
+ OneKeyMainThreadDecode.noteDiskMiss()
630
+ return nil
631
+ }
632
+ guard size <= OneKeyMainThreadDecode.maximumEncodedBytes else {
633
+ OneKeyMainThreadDecode.noteLimitRejection()
634
+ return nil
635
+ }
636
+ guard let data = try? Data(contentsOf: URL(fileURLWithPath: path)),
637
+ !data.isEmpty else {
638
+ OneKeyMainThreadDecode.noteDiskMiss()
639
+ return nil
640
+ }
641
+ guard data.count <= OneKeyMainThreadDecode.maximumEncodedBytes else {
642
+ OneKeyMainThreadDecode.noteLimitRejection()
643
+ return nil
644
+ }
645
+ diskImage = SDImageCacheDecodeImageData(
646
+ data,
647
+ key,
648
+ [],
649
+ [.imageScaleFactor: NSNumber(value: 1.0)]
650
+ )
651
+ } else {
652
+ diskImage = diskCache.imageFromDiskCache(forKey: key)
653
+ }
654
+ if let image = diskImage,
655
+ image.cgImage?.width == request.width, image.cgImage?.height == request.height {
656
+ let result = RenderResult(image: image, mode: mode, sourceIdentity: sourceIdentity, maskAlpha: maskAlpha)
657
+ remember(result, key: key)
658
+ return result
659
+ }
660
+ if diskOnly {
661
+ OneKeyMainThreadDecode.noteDecodeFailure()
662
+ return nil
663
+ }
664
+ guard let url = bundle?.url(forResource: request.name, withExtension: "svg"),
665
+ let source = try? String(contentsOf: url, encoding: .utf8),
249
666
  let pattern = try? NSRegularExpression(pattern: #"((?:fill|stroke)\s*=\s*["'])currentColor(["'])"#) else { return nil }
250
667
  // CoreSVG interprets integer rgba alpha as an 8-bit channel; decimals retain CSS endpoints.
251
668
  let svgColor = paintColor.replacingOccurrences(of: #",(0|1)\)$"#, with: ",$1.0)", options: .regularExpression)
@@ -265,10 +682,22 @@ public final class OneKeyNamedSVG {
265
682
  width: fitted.width, height: fitted.height))
266
683
  }
267
684
  let result = RenderResult(image: output, mode: mode, sourceIdentity: sourceIdentity, maskAlpha: maskAlpha)
268
- let cost = (output.cgImage?.bytesPerRow ?? request.width * 4) * request.height
685
+ remember(result, key: key)
686
+ if (output.cgImage?.bytesPerRow ?? request.width * 4) * request.height <= 8_388_608 {
687
+ Self.diskWriter.async {
688
+ if let data = output.pngData() {
689
+ Self.rasterDiskCache.storeImageData(toDisk: data, forKey: key)
690
+ }
691
+ }
692
+ }
693
+ return result
694
+ }
695
+
696
+ private func remember(_ result: RenderResult, key: String) {
697
+ let cost = (result.image.cgImage?.bytesPerRow ?? Int(result.image.size.width) * 4) * (result.image.cgImage?.height ?? Int(result.image.size.height))
269
698
  if cost <= 8_388_608 {
270
699
  lock.lock(); defer { lock.unlock() }
271
- if let previous = cache[key] { bytes -= (previous.image.cgImage?.bytesPerRow ?? request.width * 4) * request.height }
700
+ if let previous = cache[key] { bytes -= (previous.image.cgImage?.bytesPerRow ?? 0) * (previous.image.cgImage?.height ?? 0) }
272
701
  cache[key] = result
273
702
  recency.removeAll { $0 == key }; recency.append(key)
274
703
  bytes += cost
@@ -277,6 +706,5 @@ public final class OneKeyNamedSVG {
277
706
  if let image = cache.removeValue(forKey: oldest) { bytes -= (image.image.cgImage?.bytesPerRow ?? 0) * (image.image.cgImage?.height ?? 0) }
278
707
  }
279
708
  }
280
- return result
281
709
  }
282
710
  }