@onekeyfe/react-native-image 6.7.0-50 → 6.7.0-52

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 (24) hide show
  1. package/android/build.gradle +1 -0
  2. package/android/src/main/AndroidManifest.xml +5 -0
  3. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyIcon.kt +5 -1
  4. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImage.kt +240 -6
  5. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageCache.kt +4 -0
  6. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageGlideRegistry.kt +1 -0
  7. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageSafety.kt +41 -0
  8. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageStartupPrewarm.kt +990 -0
  9. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageStartupProvider.kt +54 -0
  10. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyMainThreadDecode.kt +541 -0
  11. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyNamedSVG.kt +758 -61
  12. package/android/src/test/java/com/margelo/nitro/onekeyimage/OneKeyStartupPrewarmTest.kt +545 -0
  13. package/ios/OneKeyIcon.swift +6 -0
  14. package/ios/OneKeyImage.swift +75 -1
  15. package/ios/OneKeyImageCache.swift +2 -0
  16. package/ios/OneKeyImageCoderBridge.m +42 -1
  17. package/ios/OneKeyImageStartupPrewarm.swift +564 -0
  18. package/ios/OneKeyMainThreadDecode.swift +338 -0
  19. package/ios/OneKeyNamedSVG.swift +380 -7
  20. package/ios/tests/OneKeyIconTests.swift +147 -0
  21. package/ios/tests/OneKeyImageInfrastructureTests.swift +263 -0
  22. package/lib/module/index.js +5 -1
  23. package/package.json +1 -1
  24. package/src/index.tsx +23 -2
@@ -1,4 +1,5 @@
1
1
  import Foundation
2
+ import QuartzCore
2
3
  import SDWebImage
3
4
  import UIKit
4
5
 
@@ -31,6 +32,12 @@ internal final class OneKeyNamedSVGBridge: NSObject {
31
32
  complete: complete
32
33
  )
33
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
+ }
34
41
  }
35
42
 
36
43
  /// Process-owned resource metadata and immutable raster cache, independent of JS runtimes.
@@ -114,6 +121,305 @@ public final class OneKeyNamedSVG {
114
121
  private var recency: [String] = []
115
122
  private var bytes = 0
116
123
 
124
+ // MARK: Startup prewarm
125
+ //
126
+ // A cold process starts with an empty memory cache, so every icon of the first
127
+ // screen would miss `cachedRender` and paint one frame late. The requests seen
128
+ // right after launch are persisted and decoded again on a background queue at
129
+ // the next process start, before JS mounts the first screen.
130
+
131
+ struct StartupIdentity: Hashable {
132
+ let name: String
133
+ let color: String
134
+ let width: Int
135
+ let height: Int
136
+ let scale: Double
137
+ }
138
+
139
+ struct StartupEntry: Codable, Equatable {
140
+ let name: String
141
+ let color: String
142
+ let width: Int
143
+ let height: Int
144
+ let scale: Double
145
+ var launch: Int
146
+
147
+ var identity: StartupIdentity {
148
+ StartupIdentity(name: name, color: color, width: width, height: height, scale: scale)
149
+ }
150
+
151
+ private enum CodingKeys: String, CodingKey {
152
+ case name
153
+ case color
154
+ case width
155
+ case height
156
+ case scale
157
+ case launch
158
+ }
159
+
160
+ init(name: String, color: String, width: Int, height: Int, scale: Double, launch: Int = 0) {
161
+ self.name = name
162
+ self.color = color
163
+ self.width = width
164
+ self.height = height
165
+ self.scale = scale
166
+ self.launch = launch
167
+ }
168
+
169
+ init(from decoder: Decoder) throws {
170
+ let container = try decoder.container(keyedBy: CodingKeys.self)
171
+ self.name = try container.decode(String.self, forKey: .name)
172
+ self.color = try container.decode(String.self, forKey: .color)
173
+ self.width = try container.decode(Int.self, forKey: .width)
174
+ self.height = try container.decode(Int.self, forKey: .height)
175
+ self.scale = try container.decode(Double.self, forKey: .scale)
176
+ self.launch = try container.decodeIfPresent(Int.self, forKey: .launch) ?? 0
177
+ }
178
+
179
+ func encode(to encoder: Encoder) throws {
180
+ var container = encoder.container(keyedBy: CodingKeys.self)
181
+ try container.encode(name, forKey: .name)
182
+ try container.encode(color, forKey: .color)
183
+ try container.encode(width, forKey: .width)
184
+ try container.encode(height, forKey: .height)
185
+ try container.encode(scale, forKey: .scale)
186
+ if launch > 0 {
187
+ try container.encode(launch, forKey: .launch)
188
+ }
189
+ }
190
+ }
191
+
192
+ struct StartupMetrics: Equatable {
193
+ var entryCount: Int = 0
194
+ var decodedCount: Int = 0
195
+ var manifestLoadMs: Double = 0
196
+ var totalMs: Double = 0
197
+ }
198
+
199
+ static let startupWindow: TimeInterval = 6
200
+ static let startupMaxDuration: TimeInterval = 60
201
+ static let startupMinimumSettledCount = 8
202
+ static let startupLimit = 96
203
+ static let startupMaxLaunchAge = 3
204
+ private static let startupFile: URL? = FileManager.default
205
+ .urls(for: .cachesDirectory, in: .userDomainMask).first?
206
+ .appendingPathComponent("onekey-named-svg-startup-v1.json")
207
+ private let startupLock = NSLock()
208
+ private var startupSeen: [StartupEntry] = []
209
+ private var startupPrevious: [StartupEntry] = []
210
+ private var startupMaxLaunch = 0
211
+ private var startupLoadedPreviousFromDisk = false
212
+ private var startupRecording: Bool?
213
+ private var startupFirstRequestAt: CFTimeInterval = 0
214
+ private var startupFlushWorkItem: DispatchWorkItem?
215
+ private var customStartupFile: URL?
216
+ private var startupMetrics = StartupMetrics()
217
+
218
+ private var activeStartupFileURL: URL? {
219
+ customStartupFile ?? Self.startupFile
220
+ }
221
+
222
+ func prewarmStartupSet() {
223
+ let start = CACurrentMediaTime()
224
+ // The manifest is needed by every main-thread fast path, with or without a list.
225
+ metadataLock.lock()
226
+ loadManifestIfNeeded()
227
+ metadataLock.unlock()
228
+ let manifestMs = (CACurrentMediaTime() - start) * 1000.0
229
+ startupLock.lock()
230
+ let file = activeStartupFileURL
231
+ startupLock.unlock()
232
+ guard let file, let data = try? Data(contentsOf: file),
233
+ let entries = try? JSONDecoder().decode([StartupEntry].self, from: data) else {
234
+ startupLock.lock()
235
+ startupMetrics = StartupMetrics(
236
+ entryCount: 0,
237
+ decodedCount: 0,
238
+ manifestLoadMs: manifestMs,
239
+ totalMs: manifestMs
240
+ )
241
+ startupLock.unlock()
242
+ return
243
+ }
244
+ let highestLaunch = entries.map(\.launch).max() ?? 0
245
+ startupLock.lock()
246
+ startupLoadedPreviousFromDisk = true
247
+ if startupPrevious.isEmpty {
248
+ startupPrevious = entries
249
+ startupMaxLaunch = max(startupMaxLaunch, highestLaunch)
250
+ }
251
+ startupLock.unlock()
252
+ var decodedCount = 0
253
+ let bounded = entries.prefix(Self.startupLimit)
254
+ for entry in bounded {
255
+ autoreleasepool {
256
+ if decode(Request(name: entry.name, color: entry.color, width: entry.width,
257
+ height: entry.height, scale: CGFloat(entry.scale), finalColor: false, complete: { _ in })) != nil {
258
+ decodedCount += 1
259
+ }
260
+ }
261
+ }
262
+ let totalMs = (CACurrentMediaTime() - start) * 1000.0
263
+ startupLock.lock()
264
+ startupMetrics = StartupMetrics(
265
+ entryCount: bounded.count,
266
+ decodedCount: decodedCount,
267
+ manifestLoadMs: manifestMs,
268
+ totalMs: totalMs
269
+ )
270
+ startupLock.unlock()
271
+ NSLog(
272
+ "[OneKeyImageStartupMetrics] iconPrewarm entries=%d decoded=%d manifestMs=%.3f totalMs=%.3f",
273
+ bounded.count,
274
+ decodedCount,
275
+ manifestMs,
276
+ totalMs
277
+ )
278
+ }
279
+
280
+ private func noteStartupRequest(name: String, color: String, width: Int, height: Int, scale: CGFloat) {
281
+ guard (1...4096).contains(width), (1...4096).contains(height),
282
+ scale.isFinite, scale > 0, Self.isValidColor(color) else { return }
283
+ let identity = StartupIdentity(name: name, color: color, width: width, height: height, scale: Double(scale))
284
+ startupLock.lock()
285
+ defer { startupLock.unlock() }
286
+ if startupRecording == false { return }
287
+ let now = CACurrentMediaTime()
288
+ if startupRecording == nil {
289
+ startupRecording = true
290
+ startupFirstRequestAt = now
291
+ }
292
+ guard startupSeen.count < Self.startupLimit,
293
+ !startupSeen.contains(where: { $0.identity == identity }) else { return }
294
+ startupSeen.append(
295
+ StartupEntry(name: name, color: color, width: width, height: height, scale: Double(scale), launch: 0)
296
+ )
297
+ startupFlushWorkItem?.cancel()
298
+ let item = DispatchWorkItem { [weak self] in
299
+ self?.persistStartupSet(forceClose: false)
300
+ }
301
+ startupFlushWorkItem = item
302
+ Self.diskWriter.asyncAfter(deadline: .now() + Self.startupWindow, execute: item)
303
+ }
304
+
305
+ private func persistStartupSet(forceClose: Bool) {
306
+ startupLock.lock()
307
+ guard startupRecording == true else {
308
+ startupLock.unlock()
309
+ return
310
+ }
311
+ let file = activeStartupFileURL
312
+ if !startupLoadedPreviousFromDisk {
313
+ startupLoadedPreviousFromDisk = true
314
+ if startupPrevious.isEmpty,
315
+ let file,
316
+ let data = try? Data(contentsOf: file),
317
+ let loaded = try? JSONDecoder().decode([StartupEntry].self, from: data) {
318
+ startupPrevious = loaded
319
+ startupMaxLaunch = max(startupMaxLaunch, loaded.map(\.launch).max() ?? 0)
320
+ }
321
+ }
322
+ let elapsed = CACurrentMediaTime() - startupFirstRequestAt
323
+ let shouldClose =
324
+ forceClose
325
+ || startupSeen.count >= Self.startupMinimumSettledCount
326
+ || startupSeen.count >= Self.startupLimit
327
+ || elapsed >= Self.startupMaxDuration
328
+
329
+ let seenIdentities = Set(startupSeen.map(\.identity))
330
+ let previousIdentities = startupPrevious.map(\.identity)
331
+ let currentIdentities = startupSeen.map(\.identity)
332
+ let allPreviousAtMaxLaunch = startupPrevious.allSatisfy { $0.launch == startupMaxLaunch }
333
+ let steadyStateUnchanged =
334
+ !startupPrevious.isEmpty
335
+ && currentIdentities == previousIdentities
336
+ && allPreviousAtMaxLaunch
337
+
338
+ let nextLaunch = steadyStateUnchanged ? startupMaxLaunch : (startupMaxLaunch + 1)
339
+ let currentStamped = startupSeen.map { entry -> StartupEntry in
340
+ var copy = entry
341
+ copy.launch = nextLaunch
342
+ return copy
343
+ }
344
+ // This launch's first screen leads; recent earlier entries stay warm until aged out.
345
+ let retainedPrevious = startupPrevious.filter { entry in
346
+ !seenIdentities.contains(entry.identity) && (nextLaunch - entry.launch) < Self.startupMaxLaunchAge
347
+ }
348
+ let merged = Array((currentStamped + retainedPrevious).prefix(Self.startupLimit))
349
+
350
+ if shouldClose {
351
+ startupRecording = false
352
+ startupFlushWorkItem = nil
353
+ startupSeen = []
354
+ startupPrevious = merged
355
+ startupMaxLaunch = nextLaunch
356
+ }
357
+ startupLock.unlock()
358
+
359
+ guard !steadyStateUnchanged, let file,
360
+ let data = try? JSONEncoder().encode(merged) else { return }
361
+ try? data.write(to: file, options: .atomic)
362
+ }
363
+
364
+ func startupMetricsSnapshot() -> StartupMetrics {
365
+ startupLock.lock()
366
+ defer { startupLock.unlock() }
367
+ return startupMetrics
368
+ }
369
+
370
+ func flushStartupForTesting(forceClose: Bool = true) {
371
+ Self.diskWriter.sync {
372
+ self.startupLock.lock()
373
+ self.startupFlushWorkItem?.cancel()
374
+ self.startupFlushWorkItem = nil
375
+ self.startupLock.unlock()
376
+ self.persistStartupSet(forceClose: forceClose)
377
+ }
378
+ }
379
+
380
+ func resetStartupForTesting(fileURL: URL? = nil, keepPreviousFromDisk: Bool = false) {
381
+ Self.diskWriter.sync {
382
+ self.startupLock.lock()
383
+ self.startupFlushWorkItem?.cancel()
384
+ self.startupFlushWorkItem = nil
385
+ self.startupSeen = []
386
+ if !keepPreviousFromDisk {
387
+ self.startupPrevious = []
388
+ self.startupMaxLaunch = 0
389
+ self.startupLoadedPreviousFromDisk = false
390
+ }
391
+ self.startupRecording = nil
392
+ self.startupFirstRequestAt = 0
393
+ self.customStartupFile = fileURL
394
+ self.startupMetrics = StartupMetrics()
395
+ self.startupLock.unlock()
396
+ }
397
+ }
398
+
399
+ func clearMemoryCacheForTesting() {
400
+ lock.lock()
401
+ cache.removeAll()
402
+ recency.removeAll()
403
+ bytes = 0
404
+ lock.unlock()
405
+ }
406
+
407
+ func rasterDiskCachePathForTesting(name: String, color: String, width: Int,
408
+ height: Int, scale: CGFloat) -> String? {
409
+ guard let channels = Self.channels(color) else { return nil }
410
+ metadataLock.lock()
411
+ loadManifestIfNeeded()
412
+ let entry = metadata?[name]
413
+ metadataLock.unlock()
414
+ guard let digest = entry?["digest"] as? String else { return nil }
415
+ let mode = (entry?["recolorMode"] as? String).flatMap(RecolorMode.init(rawValue:)) ?? .raster
416
+ let key = Self.renderKey(
417
+ name: name, digest: digest, width: width, height: height,
418
+ scale: scale, mode: mode, color: color, channels: channels
419
+ ).key
420
+ return Self.rasterDiskCache.cachePath(forKey: key)
421
+ }
422
+
117
423
  public func cancel(owner: AnyObject) {
118
424
  lock.lock(); defer { lock.unlock() }
119
425
  let key = ObjectIdentifier(owner)
@@ -151,6 +457,7 @@ public final class OneKeyNamedSVG {
151
457
  /// manifest loading, so remounted and recycled views paint in the same frame.
152
458
  public func cachedRender(name: String, color: String, width: Int, height: Int,
153
459
  scale: CGFloat) -> RenderResult? {
460
+ noteStartupRequest(name: name, color: color, width: width, height: height, scale: scale)
154
461
  guard let channels = Self.channels(color), metadataLock.try() else { return nil }
155
462
  let entry = metadata?[name]
156
463
  metadataLock.unlock()
@@ -189,12 +496,32 @@ public final class OneKeyNamedSVG {
189
496
 
190
497
  public func request(owner: AnyObject, name: String, color: String, width: Int,
191
498
  height: Int, scale: CGFloat, complete: @escaping (UIImage?) -> Void) {
499
+ if Thread.isMainThread {
500
+ if let hit = cachedRender(name: name, color: color, width: width, height: height, scale: scale)
501
+ ?? diskRender(name: name, color: color, width: width, height: height, scale: scale) {
502
+ cancel(owner: owner)
503
+ complete(hit.finalImage(color))
504
+ return
505
+ }
506
+ } else {
507
+ noteStartupRequest(name: name, color: color, width: width, height: height, scale: scale)
508
+ }
192
509
  enqueue(owner: owner, name: name, color: color, width: width, height: height, scale: scale,
193
510
  finalColor: true) { complete($0?.image) }
194
511
  }
195
512
 
196
513
  public func requestRender(owner: AnyObject, name: String, color: String, width: Int,
197
514
  height: Int, scale: CGFloat, complete: @escaping (RenderResult?) -> Void) {
515
+ if Thread.isMainThread {
516
+ if let hit = cachedRender(name: name, color: color, width: width, height: height, scale: scale)
517
+ ?? diskRender(name: name, color: color, width: width, height: height, scale: scale) {
518
+ cancel(owner: owner)
519
+ complete(hit)
520
+ return
521
+ }
522
+ } else {
523
+ noteStartupRequest(name: name, color: color, width: width, height: height, scale: scale)
524
+ }
198
525
  enqueue(owner: owner, name: name, color: color, width: width, height: height, scale: scale,
199
526
  finalColor: false, complete: complete)
200
527
  }
@@ -229,18 +556,46 @@ public final class OneKeyNamedSVG {
229
556
  }
230
557
  }
231
558
 
232
- private func decode(_ request: Request) -> RenderResult? {
559
+ /// Main-thread path for a memory miss: a small icon (<= 192px edge and <= 32 KiB
560
+ /// encoded raster on disk) is read and bound in the same frame. It never parses
561
+ /// SVG, loads the manifest or waits for a lock; any of those leaves the miss to workers.
562
+ public func diskRender(name: String, color: String, width: Int, height: Int,
563
+ scale: CGFloat) -> RenderResult? {
564
+ guard width > 0, height > 0,
565
+ width <= OneKeyMainThreadDecode.maximumIconEdge,
566
+ height <= OneKeyMainThreadDecode.maximumIconEdge else { return nil }
567
+ return OneKeyMainThreadDecode.run {
568
+ decode(Request(name: name, color: color, width: width, height: height, scale: scale,
569
+ finalColor: false, complete: { _ in }), diskOnly: true)
570
+ }
571
+ }
572
+
573
+ private func decode(_ request: Request, diskOnly: Bool = false) -> RenderResult? {
233
574
  guard (1...4096).contains(request.width), (1...4096).contains(request.height),
234
575
  request.width * request.height <= 4_194_304, request.scale.isFinite,
235
576
  request.scale > 0,
236
577
  let channels = Self.channels(request.color) else { return nil }
237
- metadataLock.lock()
238
- loadManifestIfNeeded()
578
+ if diskOnly {
579
+ guard metadataLock.try() else {
580
+ OneKeyMainThreadDecode.noteLockContention()
581
+ return nil
582
+ }
583
+ guard metadata != nil else {
584
+ metadataLock.unlock()
585
+ OneKeyMainThreadDecode.noteDiskMiss()
586
+ return nil
587
+ }
588
+ } else {
589
+ metadataLock.lock()
590
+ loadManifestIfNeeded()
591
+ }
239
592
  let entry = metadata?[request.name]
240
593
  let bundle = resourceBundle
241
594
  metadataLock.unlock()
242
- guard let digest = entry?["digest"] as? String,
243
- let url = bundle?.url(forResource: request.name, withExtension: "svg") else { return nil }
595
+ guard let digest = entry?["digest"] as? String else {
596
+ if diskOnly { OneKeyMainThreadDecode.noteDiskMiss() }
597
+ return nil
598
+ }
244
599
  let mode = (entry?["recolorMode"] as? String).flatMap(RecolorMode.init(rawValue:)) ?? .raster
245
600
  let (sourceIdentity, key, maskAlpha) = Self.renderKey(
246
601
  name: request.name, digest: digest, width: request.width, height: request.height,
@@ -257,8 +612,21 @@ public final class OneKeyNamedSVG {
257
612
  lock.unlock(); return image
258
613
  }
259
614
  lock.unlock()
260
- // Only workers access disk. The source digest and all raster inputs are in the key.
615
+ // The source digest and all raster inputs are in the key; diskOnly bounds encoded byte size.
261
616
  let diskCache = Self.rasterDiskCache
617
+ if diskOnly {
618
+ guard let path = diskCache.cachePath(forKey: key),
619
+ let attributes = try? FileManager.default.attributesOfItem(atPath: path),
620
+ let size = (attributes[.size] as? NSNumber)?.intValue,
621
+ size > 0 else {
622
+ OneKeyMainThreadDecode.noteDiskMiss()
623
+ return nil
624
+ }
625
+ guard size <= OneKeyMainThreadDecode.maximumEncodedBytes else {
626
+ OneKeyMainThreadDecode.noteLimitRejection()
627
+ return nil
628
+ }
629
+ }
262
630
  let diskImage = diskCache.imageFromDiskCache(forKey: key)
263
631
  if let image = diskImage,
264
632
  image.cgImage?.width == request.width, image.cgImage?.height == request.height {
@@ -266,7 +634,12 @@ public final class OneKeyNamedSVG {
266
634
  remember(result, key: key)
267
635
  return result
268
636
  }
269
- guard let source = try? String(contentsOf: url, encoding: .utf8),
637
+ if diskOnly {
638
+ OneKeyMainThreadDecode.noteDecodeFailure()
639
+ return nil
640
+ }
641
+ guard let url = bundle?.url(forResource: request.name, withExtension: "svg"),
642
+ let source = try? String(contentsOf: url, encoding: .utf8),
270
643
  let pattern = try? NSRegularExpression(pattern: #"((?:fill|stroke)\s*=\s*["'])currentColor(["'])"#) else { return nil }
271
644
  // CoreSVG interprets integer rgba alpha as an 8-bit channel; decimals retain CSS endpoints.
272
645
  let svgColor = paintColor.replacingOccurrences(of: #",(0|1)\)$"#, with: ",$1.0)", options: .regularExpression)
@@ -515,4 +515,151 @@ final class OneKeyIconTests: XCTestCase {
515
515
  try save(screenshot, name: "ios-production-gallery")
516
516
  gallery.forEach { $0.onDropView() }
517
517
  }
518
+
519
+ func testStartupPrewarmDiskRenderAndSynchronousBridgeRequest() throws {
520
+ let tempFile = FileManager.default.temporaryDirectory
521
+ .appendingPathComponent("onekey-icon-startup-test-\(UUID().uuidString).json")
522
+ defer {
523
+ OneKeyNamedSVG.shared.resetStartupForTesting(fileURL: nil)
524
+ try? FileManager.default.removeItem(at: tempFile)
525
+ }
526
+ OneKeyNamedSVG.shared.resetStartupForTesting(fileURL: tempFile)
527
+ OneKeyMainThreadDecode.resetForTesting()
528
+
529
+ // Warm one raster to disk so diskRender and prewarm can replay it.
530
+ let disk = SDImageCache(namespace: "onekey-named-svg-raster-v1")
531
+ _ = try XCTUnwrap(resolve("DotVerSolid", color: "rgba(0,0,0,1)", width: 48, height: 48, scale: 2))
532
+ eventually("Disk raster written for DotVerSolid 48x48") {
533
+ OneKeyNamedSVG.shared.clearMemoryCacheForTesting()
534
+ return OneKeyNamedSVG.shared.diskRender(
535
+ name: "DotVerSolid",
536
+ color: "rgba(0,0,0,1)",
537
+ width: 48,
538
+ height: 48,
539
+ scale: 2
540
+ ) != nil
541
+ }
542
+ _ = disk
543
+
544
+ // 1. Synchronous callback on OneKeyNamedSVGBridge.request (BottomTabs path).
545
+ var syncCallbackFired = false
546
+ let owner = NSObject()
547
+ OneKeyNamedSVGBridge.request(
548
+ owner: owner,
549
+ name: "DotVerSolid",
550
+ color: "rgba(0,0,0,1)",
551
+ width: 48,
552
+ height: 48,
553
+ scale: 2
554
+ ) { image in
555
+ XCTAssertNotNil(image)
556
+ syncCallbackFired = true
557
+ }
558
+ XCTAssertTrue(syncCallbackFired, "Bridge request must invoke completion synchronously on main thread when cached")
559
+
560
+ // 2. diskRender size bound (>192px and >32KiB rejected) and metrics recording.
561
+ OneKeyNamedSVG.shared.clearMemoryCacheForTesting()
562
+ OneKeyMainThreadDecode.resetForTesting()
563
+ XCTAssertNil(
564
+ OneKeyNamedSVG.shared.diskRender(
565
+ name: "DotVerSolid",
566
+ color: "rgba(0,0,0,1)",
567
+ width: 200,
568
+ height: 200,
569
+ scale: 2
570
+ )
571
+ )
572
+ let rasterPath = try XCTUnwrap(
573
+ OneKeyNamedSVG.shared.rasterDiskCachePathForTesting(
574
+ name: "DotVerSolid",
575
+ color: "rgba(0,0,0,1)",
576
+ width: 48,
577
+ height: 48,
578
+ scale: 2
579
+ )
580
+ )
581
+ let rasterURL = URL(fileURLWithPath: rasterPath)
582
+ let originalRasterData = try Data(contentsOf: rasterURL)
583
+ try Data(repeating: 0, count: OneKeyMainThreadDecode.maximumEncodedBytes + 1024)
584
+ .write(to: rasterURL, options: .atomic)
585
+ defer {
586
+ try? originalRasterData.write(to: rasterURL, options: .atomic)
587
+ }
588
+ XCTAssertNil(
589
+ OneKeyNamedSVG.shared.diskRender(
590
+ name: "DotVerSolid",
591
+ color: "rgba(0,0,0,1)",
592
+ width: 48,
593
+ height: 48,
594
+ scale: 2
595
+ )
596
+ )
597
+ try originalRasterData.write(to: rasterURL, options: .atomic)
598
+ XCTAssertNotNil(
599
+ OneKeyNamedSVG.shared.diskRender(
600
+ name: "DotVerSolid",
601
+ color: "rgba(0,0,0,1)",
602
+ width: 48,
603
+ height: 48,
604
+ scale: 2
605
+ )
606
+ )
607
+ let decodeMetrics = OneKeyMainThreadDecode.metricsSnapshot()
608
+ XCTAssertEqual(decodeMetrics.hits, 1)
609
+ XCTAssertEqual(decodeMetrics.limitRejections, 1)
610
+
611
+ // 3. App Lock multi-burst window + launch-generation eviction.
612
+ OneKeyNamedSVG.shared.resetStartupForTesting(fileURL: tempFile)
613
+ _ = OneKeyNamedSVG.shared.cachedRender(
614
+ name: "DotVerSolid",
615
+ color: "rgba(0,0,0,1)",
616
+ width: 48,
617
+ height: 48,
618
+ scale: 2
619
+ )
620
+ // Simulate first 3s quiet flush while still on App Lock (< 8 icons): recording stays open.
621
+ OneKeyNamedSVG.shared.flushStartupForTesting(forceClose: false)
622
+ _ = OneKeyNamedSVG.shared.cachedRender(
623
+ name: "BotIllus",
624
+ color: "rgba(0,0,0,1)",
625
+ width: 48,
626
+ height: 48,
627
+ scale: 2
628
+ )
629
+ OneKeyNamedSVG.shared.flushStartupForTesting(forceClose: true)
630
+
631
+ let firstLaunchEntries = try JSONDecoder().decode(
632
+ [OneKeyNamedSVG.StartupEntry].self,
633
+ from: Data(contentsOf: tempFile)
634
+ )
635
+ XCTAssertEqual(firstLaunchEntries.map(\.name), ["DotVerSolid", "BotIllus"])
636
+ XCTAssertEqual(firstLaunchEntries.map(\.launch), [1, 1])
637
+
638
+ // Simulate prewarm on launch 2, then only "BotIllus" is seen for 3 launches.
639
+ for expectedLaunch in 2...4 {
640
+ OneKeyNamedSVG.shared.clearMemoryCacheForTesting()
641
+ OneKeyNamedSVG.shared.resetStartupForTesting(fileURL: tempFile)
642
+ OneKeyNamedSVG.shared.prewarmStartupSet()
643
+ XCTAssertGreaterThanOrEqual(OneKeyNamedSVG.shared.startupMetricsSnapshot().entryCount, 1)
644
+ _ = OneKeyNamedSVG.shared.cachedRender(
645
+ name: "BotIllus",
646
+ color: "rgba(0,0,0,1)",
647
+ width: 48,
648
+ height: 48,
649
+ scale: 2
650
+ )
651
+ OneKeyNamedSVG.shared.flushStartupForTesting(forceClose: true)
652
+ let currentEntries = try JSONDecoder().decode(
653
+ [OneKeyNamedSVG.StartupEntry].self,
654
+ from: Data(contentsOf: tempFile)
655
+ )
656
+ if expectedLaunch < 4 {
657
+ XCTAssertEqual(currentEntries.map(\.name), ["BotIllus", "DotVerSolid"])
658
+ } else {
659
+ // Launch 4: DotVerSolid (launch 1) has age 4 - 1 == 3 >= startupMaxLaunchAge(3) and is evicted.
660
+ XCTAssertEqual(currentEntries.map(\.name), ["BotIllus"])
661
+ XCTAssertEqual(currentEntries.first?.launch, 4)
662
+ }
663
+ }
664
+ }
518
665
  }