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

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
@@ -0,0 +1,545 @@
1
+ package com.margelo.nitro.onekeyimage
2
+
3
+ import android.content.res.AssetManager
4
+ import android.graphics.Bitmap
5
+ import org.junit.After
6
+ import org.junit.Assert.assertEquals
7
+ import org.junit.Assert.assertFalse
8
+ import org.junit.Assert.assertNotNull
9
+ import org.junit.Assert.assertNull
10
+ import org.junit.Assert.assertSame
11
+ import org.junit.Assert.assertTrue
12
+ import org.junit.Before
13
+ import org.junit.Test
14
+ import java.io.ByteArrayOutputStream
15
+ import java.io.DataOutputStream
16
+ import java.io.File
17
+ import java.nio.file.Files
18
+ import java.util.Base64
19
+ import java.util.concurrent.CountDownLatch
20
+ import java.util.zip.CRC32
21
+ import java.util.zip.DeflaterOutputStream
22
+ import kotlin.concurrent.thread
23
+
24
+ class OneKeyStartupPrewarmTest {
25
+ private lateinit var tempDir: File
26
+
27
+ private fun dummyBitmap(): Bitmap {
28
+ val unsafeClass = Class.forName("sun.misc.Unsafe")
29
+ val theUnsafe = unsafeClass.getDeclaredField("theUnsafe").apply { isAccessible = true }.get(null)
30
+ val allocateInstance = unsafeClass.getMethod("allocateInstance", Class::class.java)
31
+ return allocateInstance.invoke(theUnsafe, Bitmap::class.java) as Bitmap
32
+ }
33
+
34
+ private fun dummyAssetManager(): AssetManager {
35
+ val unsafeClass = Class.forName("sun.misc.Unsafe")
36
+ val theUnsafe = unsafeClass.getDeclaredField("theUnsafe").apply { isAccessible = true }.get(null)
37
+ val allocateInstance = unsafeClass.getMethod("allocateInstance", Class::class.java)
38
+ return allocateInstance.invoke(theUnsafe, AssetManager::class.java) as AssetManager
39
+ }
40
+
41
+ private fun createValidPng(width: Int, height: Int): ByteArray {
42
+ val out = ByteArrayOutputStream()
43
+ out.write(byteArrayOf(0x89.toByte(), 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a))
44
+ fun writeChunk(type: String, payload: ByteArray) {
45
+ val dos = DataOutputStream(out)
46
+ val typeBytes = type.toByteArray(Charsets.US_ASCII)
47
+ dos.writeInt(payload.size)
48
+ dos.write(typeBytes)
49
+ dos.write(payload)
50
+ val crc = CRC32().apply {
51
+ update(typeBytes)
52
+ update(payload)
53
+ }
54
+ dos.writeInt(crc.value.toInt())
55
+ }
56
+ val ihdr = ByteArrayOutputStream().also {
57
+ DataOutputStream(it).apply {
58
+ writeInt(width)
59
+ writeInt(height)
60
+ writeByte(8) // bit depth
61
+ writeByte(6) // RGBA
62
+ writeByte(0)
63
+ writeByte(0)
64
+ writeByte(0)
65
+ }
66
+ }.toByteArray()
67
+ writeChunk("IHDR", ihdr)
68
+ val idat = ByteArrayOutputStream().also { raw ->
69
+ DeflaterOutputStream(raw).use { deflater ->
70
+ deflater.write(ByteArray(height * (1 + minOf(width, 4) * 4)))
71
+ }
72
+ }.toByteArray()
73
+ writeChunk("IDAT", idat)
74
+ writeChunk("IEND", ByteArray(0))
75
+ return out.toByteArray()
76
+ }
77
+
78
+ @Before
79
+ fun setUp() {
80
+ tempDir = Files.createTempDirectory("onekey-android-startup-test").toFile()
81
+ OneKeyMainThreadDecode.isEnabled = true
82
+ OneKeyMainThreadDecode.mainThreadCheckOverrideForTesting = { true }
83
+ OneKeyMainThreadDecode.resetForTesting()
84
+ OneKeyImageStartupPrewarm.bitmapByteCountOverrideForTesting = { 4096L }
85
+ OneKeyImageStartupPrewarm.bitmapDecoderOverrideForTesting = { _, _, _, _, _, _ ->
86
+ dummyBitmap()
87
+ }
88
+ OneKeyImageStartupPrewarm.resetForTesting(
89
+ file = File(tempDir, "onekey-image-startup-v1.json"),
90
+ cacheDir = tempDir,
91
+ )
92
+ OneKeyNamedSVG.bitmapByteCountOverrideForTesting = { 4096L }
93
+ OneKeyNamedSVG.diskPngDecoderOverrideForTesting = { file, _, _ ->
94
+ if (file.isFile && file.length() > 0L) dummyBitmap() else null
95
+ }
96
+ OneKeyNamedSVG.clearMemoryCacheForTesting()
97
+ OneKeyNamedSVG.setManifestFallbackForTesting(
98
+ mapOf(
99
+ "DotVerSolid" to OneKeyNamedSVG.ManifestEntry(
100
+ digest = "digest-dot",
101
+ mode = OneKeyNamedSVG.RecolorMode.SINGLE,
102
+ ),
103
+ "HomeOutline" to OneKeyNamedSVG.ManifestEntry(
104
+ digest = "digest-home",
105
+ mode = OneKeyNamedSVG.RecolorMode.SINGLE,
106
+ ),
107
+ "ChartPositionOutline" to OneKeyNamedSVG.ManifestEntry(
108
+ digest = "digest-chart",
109
+ mode = OneKeyNamedSVG.RecolorMode.MULTIPLE,
110
+ ),
111
+ "BotIllus" to OneKeyNamedSVG.ManifestEntry(
112
+ digest = "digest-bot",
113
+ mode = OneKeyNamedSVG.RecolorMode.FIXED,
114
+ ),
115
+ ),
116
+ )
117
+ OneKeyNamedSVG.resetStartupForTesting(
118
+ file = File(tempDir, "onekey-named-svg-startup-v1.json"),
119
+ cacheDir = tempDir,
120
+ )
121
+ }
122
+
123
+ @After
124
+ fun tearDown() {
125
+ OneKeyMainThreadDecode.mainThreadCheckOverrideForTesting = null
126
+ OneKeyMainThreadDecode.resetForTesting()
127
+ OneKeyImageStartupPrewarm.bitmapDecoderOverrideForTesting = null
128
+ OneKeyImageStartupPrewarm.bitmapByteCountOverrideForTesting = null
129
+ OneKeyImageStartupPrewarm.resetForTesting()
130
+ OneKeyNamedSVG.diskPngDecoderOverrideForTesting = null
131
+ OneKeyNamedSVG.bitmapByteCountOverrideForTesting = null
132
+ OneKeyNamedSVG.setManifestFallbackForTesting(null)
133
+ OneKeyNamedSVG.resetStartupForTesting()
134
+ tempDir.deleteRecursively()
135
+ }
136
+
137
+ @Test
138
+ fun mainThreadDecodeEnforcesBudgetAndTracksMetrics() {
139
+ // 1. Hit and miss tracking
140
+ val hit = OneKeyMainThreadDecode.run { 42 }
141
+ assertEquals(42, hit)
142
+ val miss = OneKeyMainThreadDecode.run<Int> { null }
143
+ assertNull(miss)
144
+
145
+ var s = OneKeyMainThreadDecode.metricsSnapshot()
146
+ assertEquals(2, s.attempts)
147
+ assertEquals(1, s.hits)
148
+ assertEquals(1, s.misses)
149
+ assertEquals(0, s.budgetRejections)
150
+
151
+ // 2. Exhaust budget within a 1s window
152
+ OneKeyMainThreadDecode.setBudgetForTesting(budgetNs = 1_000_000L, windowNs = 1_000_000_000L)
153
+ val slowHit = OneKeyMainThreadDecode.run {
154
+ val deadline = System.nanoTime() + 2_000_000L
155
+ while (System.nanoTime() < deadline) {
156
+ // Busy wait 2ms
157
+ }
158
+ true
159
+ }
160
+ assertEquals(true, slowHit)
161
+
162
+ val rejected = OneKeyMainThreadDecode.run { true }
163
+ assertNull(rejected)
164
+ s = OneKeyMainThreadDecode.metricsSnapshot()
165
+ assertEquals(1, s.budgetRejections)
166
+ }
167
+
168
+ @Test
169
+ fun mainThreadDecodePromotesSmallLocalAndCachedImagesAndRejectsOversized() {
170
+ OneKeyMainThreadDecode.setBudgetForTesting(budgetNs = 1_000_000_000L, windowNs = 10_000_000_000L)
171
+ val smallPng = OneKeyBlockieAvatar.png("onekey-avatar://blockie/v1/0xabc123")
172
+ val fileImg = File(tempDir, "small.png").apply { writeBytes(smallPng) }
173
+ val fileUrl = "file://${fileImg.absolutePath}"
174
+
175
+ // 1. Small local file:// promotes within budget
176
+ val promotedFile = OneKeyMainThreadDecode.run {
177
+ if (OneKeyMainThreadDecode.promoteToMemory(tempDir, fileUrl, fileUrl, 64, 64, false)) true else null
178
+ }
179
+ assertEquals(true, promotedFile)
180
+ assertNotNull(OneKeyImageStartupPrewarm.cachedBitmap(fileUrl, 64, 64, false))
181
+
182
+ // 2. Small data: URI promotes within budget
183
+ val dataUri = "data:image/png;base64," + Base64.getEncoder().encodeToString(smallPng)
184
+ val promotedData = OneKeyMainThreadDecode.run {
185
+ if (OneKeyMainThreadDecode.promoteToMemory(tempDir, dataUri, dataUri, 48, 48, true)) true else null
186
+ }
187
+ assertEquals(true, promotedData)
188
+ assertNotNull(OneKeyImageStartupPrewarm.cachedBitmap(dataUri, 48, 48, true))
189
+
190
+ // 3. Target > 256px rejected
191
+ assertFalse(OneKeyMainThreadDecode.promoteToMemory(tempDir, fileUrl, fileUrl, 300, 300, false))
192
+
193
+ // 4. Source > 512px rejected
194
+ val largeSourcePng = createValidPng(600, 600)
195
+ val largeSourceFile = File(tempDir, "large-source.png").apply { writeBytes(largeSourcePng) }
196
+ val largeSourceUrl = "file://${largeSourceFile.absolutePath}"
197
+ assertFalse(OneKeyMainThreadDecode.promoteToMemory(tempDir, largeSourceUrl, largeSourceUrl, 64, 64, false))
198
+
199
+ // 5. File > 32KiB rejected
200
+ val hugeBytes = smallPng + ByteArray(33 * 1024)
201
+ val hugeFile = File(tempDir, "huge.png").apply { writeBytes(hugeBytes) }
202
+ val hugeUrl = "file://${hugeFile.absolutePath}"
203
+ assertFalse(OneKeyMainThreadDecode.promoteToMemory(tempDir, hugeUrl, hugeUrl, 64, 64, false))
204
+ assertTrue(OneKeyMainThreadDecode.metricsSnapshot().limitRejections >= 3)
205
+ }
206
+
207
+ @Test
208
+ fun imageStartupPrewarmHashesKeysEvictsByLaunchAndRespectsQuietWindow() {
209
+ val startupJsonFile = File(tempDir, "onekey-image-startup-v1.json")
210
+ val glideCacheDir = File(tempDir, OneKeyImageStartupPrewarm.GLIDE_DISK_CACHE_DIR).apply { mkdirs() }
211
+
212
+ val secretAvatarUrl = "onekey-avatar://blockie/v1/0xdeadbeefcafebabe1234567890"
213
+ val remoteUrl = "https://cdn.onekey.so/banner-secret-token.png"
214
+ val pngBytes = OneKeyBlockieAvatar.png(secretAvatarUrl)
215
+
216
+ // Seed Glide disk cache for remoteUrl
217
+ val remoteSafeKey = requireNotNull(OneKeyImageStartupPrewarm.glideDataSafeKey(remoteUrl))
218
+ File(glideCacheDir, "$remoteSafeKey.0").writeBytes(pngBytes)
219
+
220
+ // 1. Single entry (below MIN_SETTLED_COUNT = 2) keeps window open on non-forced debounce
221
+ OneKeyImageStartupPrewarm.note(
222
+ cacheDir = tempDir,
223
+ requestUrl = secretAvatarUrl,
224
+ rawUrl = secretAvatarUrl,
225
+ headersJson = null,
226
+ cachePolicy = OneKeyImageCachePolicy.MEMORY_DISK,
227
+ width = 96,
228
+ height = 96,
229
+ round = true,
230
+ )
231
+ OneKeyImageStartupPrewarm.flushForTesting(forceClose = false)
232
+ assertFalse("Window must remain open while < 2 images seen (App Lock)", startupJsonFile.exists())
233
+
234
+ // 2. Second entry after unlocking settles and persists Launch 1
235
+ OneKeyImageStartupPrewarm.note(
236
+ cacheDir = tempDir,
237
+ requestUrl = remoteUrl,
238
+ rawUrl = remoteUrl,
239
+ headersJson = null,
240
+ cachePolicy = OneKeyImageCachePolicy.MEMORY_DISK,
241
+ width = 120,
242
+ height = 60,
243
+ round = false,
244
+ )
245
+ OneKeyImageStartupPrewarm.flushForTesting(forceClose = true)
246
+ assertTrue(startupJsonFile.isFile)
247
+
248
+ // 3. Privacy check: persisted JSON must contain zero plaintext URLs or wallet addresses
249
+ val rawJson = startupJsonFile.readText(Charsets.UTF_8)
250
+ assertFalse(rawJson.contains("0xdeadbeef"))
251
+ assertFalse(rawJson.contains("onekey-avatar"))
252
+ assertFalse(rawJson.contains("banner-secret-token"))
253
+ assertFalse(rawJson.contains("https://"))
254
+
255
+ val launch1Entries = OneKeyImageStartupPrewarm.readEntries(startupJsonFile)
256
+ assertEquals(2, launch1Entries.size)
257
+ assertTrue(launch1Entries.all { it.launch == 1 })
258
+
259
+ // 4. Prewarm loads both entries from disk into memory cache by keyHash
260
+ OneKeyImageStartupPrewarm.clearMemoryCache()
261
+ OneKeyImageStartupPrewarm.prewarmStartupSet(tempDir)
262
+ val metrics = OneKeyImageStartupPrewarm.metricsSnapshot()
263
+ assertEquals(2, metrics.entryCount)
264
+ assertEquals(2, metrics.decodedCount)
265
+ assertNotNull(OneKeyImageStartupPrewarm.cachedBitmap(secretAvatarUrl, 96, 96, true))
266
+ assertNotNull(OneKeyImageStartupPrewarm.cachedBitmap(remoteUrl, 120, 60, false))
267
+ assertNull(
268
+ "Custom headers must bypass unauthenticated prewarmed bitmaps",
269
+ OneKeyImageStartupPrewarm.cachedBitmap(
270
+ remoteUrl,
271
+ 120,
272
+ 60,
273
+ false,
274
+ headersJson = """{"Authorization":"Bearer secret"}""",
275
+ ),
276
+ )
277
+
278
+ // 5. Launch-generation eviction: after 3 launches of only remoteUrl, secretAvatarUrl is evicted
279
+ val avatarDiskSafeKey = requireNotNull(OneKeyImageStartupPrewarm.glideDataSafeKey(secretAvatarUrl))
280
+ val avatarFallbackFile = File(File(tempDir, OneKeyImageStartupPrewarm.FALLBACK_DISK_CACHE_DIR), avatarDiskSafeKey)
281
+ assertTrue("Avatar fallback file should exist after Launch 1", avatarFallbackFile.isFile)
282
+ for (expectedLaunch in 2..4) {
283
+ OneKeyImageStartupPrewarm.resetForTesting(file = startupJsonFile, cacheDir = tempDir)
284
+ OneKeyImageStartupPrewarm.note(
285
+ cacheDir = tempDir,
286
+ requestUrl = remoteUrl,
287
+ rawUrl = remoteUrl,
288
+ headersJson = null,
289
+ cachePolicy = OneKeyImageCachePolicy.MEMORY_DISK,
290
+ width = 120,
291
+ height = 60,
292
+ round = false,
293
+ )
294
+ OneKeyImageStartupPrewarm.flushForTesting(forceClose = true)
295
+ val entries = OneKeyImageStartupPrewarm.readEntries(startupJsonFile)
296
+ if (expectedLaunch < 4) {
297
+ assertEquals(2, entries.size)
298
+ assertTrue(avatarFallbackFile.isFile)
299
+ } else {
300
+ assertEquals("Stale avatar must be evicted at launch 4 (age 3)", 1, entries.size)
301
+ assertEquals(
302
+ OneKeyImageStartupPrewarm.keyHash(remoteUrl, 120, 60, false),
303
+ entries[0].keyHash,
304
+ )
305
+ assertFalse("Evicted fallback file must be cleaned from disk", avatarFallbackFile.exists())
306
+ }
307
+ }
308
+
309
+ // 6. clearDiskCache removes startup JSON and fallback disk cache directory,
310
+ // and invalidates any stale pre-clear fallback write generation.
311
+ val preClearGeneration = OneKeyImageStartupPrewarm.currentDiskClearGenerationForTesting()
312
+ OneKeyImageStartupPrewarm.clearDiskCache(tempDir)
313
+ OneKeyImageStartupPrewarm.writeFallbackDiskBytes(
314
+ cacheDir = tempDir,
315
+ safeKey = avatarDiskSafeKey,
316
+ bytes = pngBytes,
317
+ expectedGeneration = preClearGeneration,
318
+ )
319
+ assertFalse(startupJsonFile.exists())
320
+ assertFalse(File(tempDir, OneKeyImageStartupPrewarm.FALLBACK_DISK_CACHE_DIR).exists())
321
+ }
322
+
323
+ @Test
324
+ fun namedSvgDiskRenderBridgeSyncCallbackAndStartupEvictionWork() {
325
+ val startupJsonFile = File(tempDir, "onekey-named-svg-startup-v1.json")
326
+ val assets = dummyAssetManager()
327
+
328
+ // Seed disk raster PNG for DotVerSolid (key = "DotVerSolid|digest-dot|48|48|2.0|SINGLE|")
329
+ val dotKey = "DotVerSolid|digest-dot|48|48|2.0|SINGLE|"
330
+ val dotRasterFile = requireNotNull(OneKeyNamedSVG.diskRasterFile(dotKey))
331
+ dotRasterFile.parentFile?.mkdirs()
332
+ dotRasterFile.writeBytes(createValidPng(48, 48))
333
+
334
+ // 1. diskRender hits synchronously on main thread and populates memory cache
335
+ val diskHit = OneKeyNamedSVG.diskRender(assets, "DotVerSolid", "rgba(0,0,0,1)", 48, 48, 2f)
336
+ assertNotNull(diskHit)
337
+ val memHit = OneKeyNamedSVG.cachedRender("DotVerSolid", "rgba(0,0,0,1)", 48, 48, 2f)
338
+ assertSame(diskHit?.bitmap, memHit?.bitmap)
339
+
340
+ // 2. OneKeyNamedSVG.request invokes callback synchronously on main thread when cached or on disk
341
+ OneKeyNamedSVG.clearMemoryCacheForTesting()
342
+ OneKeyMainThreadDecode.resetForTesting()
343
+ var syncCallbackRan = false
344
+ var syncBitmap: Bitmap? = null
345
+ OneKeyNamedSVG.request(Any(), assets, "DotVerSolid", "rgba(0,0,0,1)", 48, 48, 2f) { bmp ->
346
+ syncCallbackRan = true
347
+ syncBitmap = bmp
348
+ }
349
+ assertTrue("OneKeyNamedSVG.request must complete synchronously on main thread", syncCallbackRan)
350
+ assertNotNull(syncBitmap)
351
+
352
+ // 3. Manifest lock contention makes diskRender return null without blocking and increments metric
353
+ OneKeyNamedSVG.clearMemoryCacheForTesting()
354
+ OneKeyMainThreadDecode.resetForTesting()
355
+ val locked = CountDownLatch(1)
356
+ val release = CountDownLatch(1)
357
+ val holder = thread {
358
+ assertTrue(OneKeyNamedSVG.tryAcquireManifestAccessLockForTesting())
359
+ locked.countDown()
360
+ release.await()
361
+ OneKeyNamedSVG.unlockManifestAccessLockForTesting()
362
+ }
363
+ locked.await()
364
+ val contendedResult = try {
365
+ OneKeyNamedSVG.diskRender(assets, "DotVerSolid", "rgba(0,0,0,1)", 48, 48, 2f)
366
+ } finally {
367
+ release.countDown()
368
+ holder.join()
369
+ }
370
+ assertNull(contendedResult)
371
+ val contendedMetrics = OneKeyMainThreadDecode.metricsSnapshot()
372
+ assertEquals(1, contendedMetrics.lockContentionMisses)
373
+ assertEquals(1, contendedMetrics.attempts)
374
+ assertEquals(1, contendedMetrics.misses)
375
+
376
+ // 4. Startup quiet window (< 8 icons stays open on non-forced flush) and 3-launch eviction
377
+ OneKeyNamedSVG.resetStartupForTesting(file = startupJsonFile, cacheDir = tempDir)
378
+ OneKeyNamedSVG.cachedRender("DotVerSolid", "rgba(0,0,0,1)", 48, 48, 2f)
379
+ OneKeyNamedSVG.flushStartupForTesting(forceClose = false)
380
+ assertFalse("Icon window must stay open when < 8 icons seen", startupJsonFile.exists())
381
+
382
+ OneKeyNamedSVG.cachedRender("HomeOutline", "rgba(0,0,0,1)", 48, 48, 2f)
383
+ OneKeyNamedSVG.flushStartupForTesting(forceClose = true)
384
+ assertEquals(2, OneKeyNamedSVG.readStartupEntries(startupJsonFile).size)
385
+
386
+ for (launch in 2..4) {
387
+ OneKeyNamedSVG.resetStartupForTesting(file = startupJsonFile, cacheDir = tempDir)
388
+ OneKeyNamedSVG.cachedRender("DotVerSolid", "rgba(0,0,0,1)", 48, 48, 2f)
389
+ OneKeyNamedSVG.flushStartupForTesting(forceClose = true)
390
+ val entries = OneKeyNamedSVG.readStartupEntries(startupJsonFile)
391
+ if (launch < 4) {
392
+ assertEquals(2, entries.size)
393
+ } else {
394
+ assertEquals(1, entries.size)
395
+ assertEquals("DotVerSolid", entries[0].name)
396
+ }
397
+ }
398
+
399
+ // 5. Oversized icon raster file (> 32KiB) is rejected by diskRender with limitRejections
400
+ OneKeyNamedSVG.clearMemoryCacheForTesting()
401
+ OneKeyMainThreadDecode.resetForTesting()
402
+ dotRasterFile.writeBytes(ByteArray(OneKeyMainThreadDecode.MAX_ENCODED_BYTES + 1024))
403
+ assertNull(OneKeyNamedSVG.diskRender(assets, "DotVerSolid", "rgba(0,0,0,1)", 48, 48, 2f))
404
+ assertEquals(1, OneKeyMainThreadDecode.metricsSnapshot().limitRejections)
405
+ }
406
+
407
+ @Test
408
+ fun exifOrientationParsingDimensionSwappingAndDensityFallbackWork() {
409
+ fun buildTiffOrientation(orientation: Int, littleEndian: Boolean): ByteArray {
410
+ val out = ByteArrayOutputStream()
411
+ fun writeU16(v: Int) {
412
+ if (littleEndian) {
413
+ out.write(v and 0xff)
414
+ out.write((v ushr 8) and 0xff)
415
+ } else {
416
+ out.write((v ushr 8) and 0xff)
417
+ out.write(v and 0xff)
418
+ }
419
+ }
420
+ fun writeU32(v: Int) {
421
+ if (littleEndian) {
422
+ out.write(v and 0xff)
423
+ out.write((v ushr 8) and 0xff)
424
+ out.write((v ushr 16) and 0xff)
425
+ out.write((v ushr 24) and 0xff)
426
+ } else {
427
+ out.write((v ushr 24) and 0xff)
428
+ out.write((v ushr 16) and 0xff)
429
+ out.write((v ushr 8) and 0xff)
430
+ out.write(v and 0xff)
431
+ }
432
+ }
433
+ out.write(if (littleEndian) "II".toByteArray() else "MM".toByteArray())
434
+ writeU16(0x002a)
435
+ writeU32(8) // IFD0 offset
436
+ writeU16(1) // 1 entry
437
+ writeU16(0x0112) // Orientation tag
438
+ writeU16(3) // SHORT
439
+ writeU32(1) // count = 1
440
+ writeU16(orientation)
441
+ writeU16(0)
442
+ writeU32(0) // next IFD
443
+ return out.toByteArray()
444
+ }
445
+
446
+ fun buildJpegWithExif(orientation: Int, littleEndian: Boolean): ByteArray {
447
+ val tiff = buildTiffOrientation(orientation, littleEndian)
448
+ val app1Payload = "Exif\u0000\u0000".toByteArray(Charsets.US_ASCII) + tiff
449
+ val segLen = app1Payload.size + 2
450
+ val out = ByteArrayOutputStream()
451
+ out.write(byteArrayOf(0xff.toByte(), 0xd8.toByte(), 0xff.toByte(), 0xe1.toByte()))
452
+ out.write((segLen ushr 8) and 0xff)
453
+ out.write(segLen and 0xff)
454
+ out.write(app1Payload)
455
+ out.write(byteArrayOf(0xff.toByte(), 0xd9.toByte()))
456
+ return out.toByteArray()
457
+ }
458
+
459
+ fun buildWebpWithExif(orientation: Int): ByteArray {
460
+ val tiff = buildTiffOrientation(orientation, littleEndian = true)
461
+ val out = ByteArrayOutputStream()
462
+ val riffSize = 4 + 8 + tiff.size + (tiff.size and 1)
463
+ fun writeLe32(v: Int) {
464
+ out.write(v and 0xff)
465
+ out.write((v ushr 8) and 0xff)
466
+ out.write((v ushr 16) and 0xff)
467
+ out.write((v ushr 24) and 0xff)
468
+ }
469
+ out.write("RIFF".toByteArray(Charsets.US_ASCII))
470
+ writeLe32(riffSize)
471
+ out.write("WEBP".toByteArray(Charsets.US_ASCII))
472
+ out.write("EXIF".toByteArray(Charsets.US_ASCII))
473
+ writeLe32(tiff.size)
474
+ out.write(tiff)
475
+ if ((tiff.size and 1) == 1) out.write(0)
476
+ return out.toByteArray()
477
+ }
478
+
479
+ val jpegRot90Le = buildJpegWithExif(orientation = 6, littleEndian = true)
480
+ val jpegRot270Be = buildJpegWithExif(orientation = 8, littleEndian = false)
481
+ val jpegRot180 = buildJpegWithExif(orientation = 3, littleEndian = true)
482
+ val webpTranspose = buildWebpWithExif(orientation = 5)
483
+
484
+ fun buildPngWithPostIdatExif(orientation: Int): ByteArray {
485
+ val basePng = createValidPng(32, 16)
486
+ val tiff = buildTiffOrientation(orientation, littleEndian = false)
487
+ // Insert eXIf chunk immediately before the 12-byte IEND chunk at the end of basePng
488
+ val iendStart = basePng.size - 12
489
+ val out = ByteArrayOutputStream()
490
+ out.write(basePng, 0, iendStart)
491
+ val dos = DataOutputStream(out)
492
+ val typeBytes = "eXIf".toByteArray(Charsets.US_ASCII)
493
+ dos.writeInt(tiff.size)
494
+ dos.write(typeBytes)
495
+ dos.write(tiff)
496
+ val crc = CRC32().apply {
497
+ update(typeBytes)
498
+ update(tiff)
499
+ }
500
+ dos.writeInt(crc.value.toInt())
501
+ out.write(basePng, iendStart, 12)
502
+ return out.toByteArray()
503
+ }
504
+ val pngPostIdatTransverse = buildPngWithPostIdatExif(orientation = 7)
505
+
506
+ assertEquals(6, OneKeyImageStartupPrewarm.extractExifOrientation(jpegRot90Le))
507
+ assertEquals(8, OneKeyImageStartupPrewarm.extractExifOrientation(jpegRot270Be))
508
+ assertEquals(3, OneKeyImageStartupPrewarm.extractExifOrientation(jpegRot180))
509
+ assertEquals(5, OneKeyImageStartupPrewarm.extractExifOrientation(webpTranspose))
510
+ assertEquals(7, OneKeyImageStartupPrewarm.extractExifOrientation(pngPostIdatTransverse))
511
+ assertEquals(1, OneKeyImageStartupPrewarm.extractExifOrientation(createValidPng(32, 32)))
512
+
513
+ // Verify decodeStaticBitmap swaps sourceWidth/sourceHeight when EXIF orientation is 5..8
514
+ var capturedWidth = 0
515
+ var capturedHeight = 0
516
+ OneKeyImageStartupPrewarm.bitmapDecoderOverrideForTesting = { _, srcW, srcH, _, _, _ ->
517
+ capturedWidth = srcW
518
+ capturedHeight = srcH
519
+ dummyBitmap()
520
+ }
521
+ OneKeyImageStartupPrewarm.decodeStaticBitmap(
522
+ bytes = jpegRot90Le,
523
+ sourceWidth = 400,
524
+ sourceHeight = 200,
525
+ targetWidth = 100,
526
+ targetHeight = 200,
527
+ round = false,
528
+ )
529
+ assertEquals(200, capturedWidth)
530
+ assertEquals(400, capturedHeight)
531
+
532
+ OneKeyImageStartupPrewarm.decodeStaticBitmap(
533
+ bytes = jpegRot180,
534
+ sourceWidth = 400,
535
+ sourceHeight = 200,
536
+ targetWidth = 100,
537
+ targetHeight = 200,
538
+ round = false,
539
+ )
540
+ assertEquals(400, capturedWidth)
541
+ assertEquals(200, capturedHeight)
542
+
543
+ assertTrue(OneKeyImageStartupPrewarm.defaultBitmapDensity() > 0)
544
+ }
545
+ }
@@ -71,6 +71,12 @@ final class HybridOneKeyIcon: HybridOneKeyIconSpec, RecyclableView {
71
71
  apply(hit, color: color)
72
72
  return
73
73
  }
74
+ if let hit = OneKeyNamedSVG.shared.diskRender(name: name, color: color,
75
+ width: Int(width), height: Int(height), scale: scale) {
76
+ displayedGeometry = geometry
77
+ apply(hit, color: color)
78
+ return
79
+ }
74
80
  OneKeyNamedSVG.shared.requestRender(owner: owner, name: name, color: color,
75
81
  width: Int(width), height: Int(height), scale: scale) { [weak self] result in
76
82
  guard let self, self.generation == revision, self.host.window != nil else { return }
@@ -321,6 +321,11 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
321
321
  onLoadStart?()
322
322
  guard Self.isCurrentRequestGeneration(generation, current: requestGeneration) else { return }
323
323
  if showMemoryCachedImageIfAvailable(requestIsActive: true) == .exact { return }
324
+ if promoteSmallCachedImageToMemory(),
325
+ showMemoryCachedImageIfAvailable(requestIsActive: true) == .exact
326
+ {
327
+ return
328
+ }
324
329
  // The pre-layout probe may have shown this identity from another thumbnail
325
330
  // key (a preload's, or an earlier layout size). Keep it on screen as the
326
331
  // placeholder while the exact rendition loads: blanking to a skeleton and
@@ -469,6 +474,13 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
469
474
  )
470
475
  )
471
476
  }
477
+ OneKeyImageStartupPrewarm.shared.note(
478
+ requestURL: url,
479
+ rawURL: rawURL,
480
+ headersJson: self.sourceHeadersJson,
481
+ cachePolicy: self.cachePolicy,
482
+ thumbnailPixelSize: thumbnailPixelSize
483
+ )
472
484
  guard self.claimTerminal(generation) else { return }
473
485
  let replacesMemoryPreview = self.clearMemoryPreviewPresentation()
474
486
  self.requestActive = false
@@ -659,6 +671,56 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
659
671
  isShowingImage && hasImage
660
672
  }
661
673
 
674
+ /// A memory miss for a small image that is already local: decode it here so
675
+ /// the probe that follows hits, instead of waiting a frame for the pipeline.
676
+ private func promoteSmallCachedImageToMemory() -> Bool {
677
+ guard (cachePolicy ?? .memoryDisk) == .memoryDisk,
678
+ OneKeyImageRequestContext.headers(from: sourceHeadersJson) == nil,
679
+ let sourceUri,
680
+ OneKeyImageSafetyPolicy.preflight(source: sourceUri) == nil,
681
+ let rawURL = URL(string: sourceUri)
682
+ else { return false }
683
+ let rawScreenScale: CGFloat = hostView.window?.screen.scale ?? UIScreen.main.scale
684
+ let screenScale = min(max(rawScreenScale, 1), 3)
685
+ guard
686
+ let thumbnailPixelSize = OneKeyImageDecodeSizing.thumbnailPixelSize(
687
+ viewSize: hostView.bounds.size,
688
+ scale: screenScale,
689
+ contentFit: contentFit ?? .cover
690
+ ),
691
+ max(thumbnailPixelSize.width, thumbnailPixelSize.height)
692
+ <= OneKeyMainThreadDecode.maximumTargetEdge
693
+ else { return false }
694
+ let displaySize =
695
+ OneKeyImageDecodeSizing.tosDisplaySize(
696
+ bounds: hostView.bounds.size,
697
+ resizeWidth: resizeWidth,
698
+ resizeHeight: resizeHeight
699
+ ) ?? 0
700
+ let requestURL =
701
+ (optimizeTos ?? true)
702
+ ? OneKeyTosURL.optimized(
703
+ rawURL: rawURL,
704
+ displaySize: displaySize,
705
+ scale: screenScale,
706
+ overscan: overscan ?? 1.1,
707
+ hasCustomIdentity: false
708
+ )
709
+ : rawURL
710
+ let promoted = OneKeyMainThreadDecode.run { () -> Bool? in
711
+ for url in requestURL == rawURL ? [requestURL] : [requestURL, rawURL]
712
+ where OneKeyMainThreadDecode.promoteToMemory(
713
+ url: url,
714
+ rawURL: rawURL,
715
+ thumbnailPixelSize: thumbnailPixelSize
716
+ ) {
717
+ return true
718
+ }
719
+ return nil
720
+ }
721
+ return promoted ?? false
722
+ }
723
+
662
724
  private func showMemoryCachedImageIfAvailable(requestIsActive: Bool) -> MemoryProbeResult {
663
725
  // JS leaves `cachePolicy` unset for the common case and Fabric then hands
664
726
  // Nitro a nil, which the request path already treats as memory-disk; the
@@ -716,7 +778,10 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
716
778
  guard let key = OneKeyImagePipeline.manager.cacheKey(for: url, context: context) else {
717
779
  return nil
718
780
  }
719
- return cache.imageFromMemoryCache(forKey: key)
781
+ if let hit = cache.imageFromMemoryCache(forKey: key) {
782
+ return hit
783
+ }
784
+ return OneKeyImageStartupPrewarm.shared.claimPrewarmedImage(forKey: key, cache: cache)
720
785
  }
721
786
 
722
787
  var exactProbes: [(variant: OneKeyImageMemoryVariant?, url: URL, size: CGSize?)] = []
@@ -745,6 +810,15 @@ final class HybridOneKeyImage: HybridOneKeyImageSpec, RecyclableView {
745
810
  if let variant = probe.variant, Self.canUseAsMemoryPreview(image) {
746
811
  OneKeyImageMemoryVariantRegistry.shared.record(variant, for: family)
747
812
  }
813
+ if requestIsActive {
814
+ OneKeyImageStartupPrewarm.shared.note(
815
+ requestURL: probe.url,
816
+ rawURL: rawURL,
817
+ headersJson: sourceHeadersJson,
818
+ cachePolicy: cachePolicy,
819
+ thumbnailPixelSize: probe.size
820
+ )
821
+ }
748
822
  displayMemoryCachedImage(
749
823
  image,
750
824
  requestIsActive: requestIsActive,
@@ -83,6 +83,7 @@ final class HybridOneKeyImageCache: HybridOneKeyImageCacheSpec {
83
83
 
84
84
  func clearDisk() throws -> Promise<Void> {
85
85
  Promise.async {
86
+ OneKeyImageStartupPrewarm.shared.clearDiskCache()
86
87
  await withCheckedContinuation { continuation in
87
88
  DispatchQueue.main.async {
88
89
  OneKeyMediaPreviewCache.shared.clearDisk { continuation.resume() }
@@ -103,6 +104,7 @@ final class HybridOneKeyImageCache: HybridOneKeyImageCacheSpec {
103
104
  SDImageCache.shared.clearMemory()
104
105
  OneKeyAvatarImageLoader.cache.clearMemory()
105
106
  OneKeyImageMemoryVariantRegistry.shared.clear()
107
+ OneKeyImageStartupPrewarm.shared.clearDiskCache()
106
108
  await withCheckedContinuation { continuation in
107
109
  DispatchQueue.main.async {
108
110
  OneKeyMediaPreviewCache.shared.clearDisk { continuation.resume() }