@onekeyfe/react-native-image 6.7.0-alpha.475 → 6.8.0-3
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/README.md +144 -86
- package/android/build.gradle +1 -0
- package/android/src/main/AndroidManifest.xml +12 -1
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyIcon.kt +5 -1
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImage.kt +240 -6
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageCache.kt +4 -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 +1 -0
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageSafety.kt +41 -0
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageStartupPrewarm.kt +1106 -0
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageStartupProvider.kt +54 -0
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyMainThreadDecode.kt +541 -0
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyMediaPreviewCache.kt +1 -1
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyNamedSVG.kt +758 -61
- package/android/src/test/java/com/margelo/nitro/onekeyimage/OneKeyStartupPrewarmTest.kt +600 -0
- package/ios/OneKeyAvatarImageLoader.swift +1 -1
- package/ios/OneKeyIcon.swift +6 -0
- package/ios/OneKeyImage.swift +85 -2
- package/ios/OneKeyImageCache.swift +2 -0
- package/ios/OneKeyImageCoderBridge.m +42 -1
- package/ios/OneKeyImageRequestContext.swift +16 -2
- package/ios/OneKeyImageStartupPrewarm.swift +602 -0
- package/ios/OneKeyMainThreadDecode.swift +338 -0
- package/ios/OneKeyMediaPreviewCache.swift +20 -12
- package/ios/OneKeyNamedSVG.swift +437 -9
- package/ios/tests/OneKeyIconTests.swift +241 -0
- package/ios/tests/OneKeyImageInfrastructureTests.swift +611 -0
- package/ios/tests/OneKeyMediaPreviewCacheTests.swift +49 -0
- package/lib/module/index.js +5 -1
- package/package.json +1 -1
- package/src/index.tsx +23 -2
|
@@ -0,0 +1,1106 @@
|
|
|
1
|
+
package com.margelo.nitro.onekeyimage
|
|
2
|
+
|
|
3
|
+
import android.content.Context
|
|
4
|
+
import android.content.res.Resources
|
|
5
|
+
import android.graphics.Bitmap
|
|
6
|
+
import android.graphics.BitmapFactory
|
|
7
|
+
import android.graphics.Canvas
|
|
8
|
+
import android.graphics.Matrix
|
|
9
|
+
import android.graphics.Paint
|
|
10
|
+
import android.graphics.PorterDuff
|
|
11
|
+
import android.graphics.PorterDuffXfermode
|
|
12
|
+
import android.util.DisplayMetrics
|
|
13
|
+
import android.util.Log
|
|
14
|
+
import com.bumptech.glide.load.Key
|
|
15
|
+
import com.bumptech.glide.signature.ObjectKey
|
|
16
|
+
import org.json.JSONArray
|
|
17
|
+
import org.json.JSONObject
|
|
18
|
+
import java.io.ByteArrayInputStream
|
|
19
|
+
import java.io.File
|
|
20
|
+
import java.security.MessageDigest
|
|
21
|
+
import java.util.Locale
|
|
22
|
+
import java.util.concurrent.Executors
|
|
23
|
+
import java.util.concurrent.ScheduledFuture
|
|
24
|
+
import java.util.concurrent.TimeUnit
|
|
25
|
+
import kotlin.math.floor
|
|
26
|
+
import kotlin.math.min
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Records the first-screen image working set and warms decoded bitmaps into a
|
|
30
|
+
* bounded process-wide memory cache at process startup.
|
|
31
|
+
*
|
|
32
|
+
* Persisted entries store only hashed cache identities (`keyHash`, `diskFile`,
|
|
33
|
+
* optional `rawDiskFile`) and target pixel dimensions — never plaintext URLs,
|
|
34
|
+
* `onekey-avatar://` wallet addresses, file paths, or `data:` payloads.
|
|
35
|
+
*/
|
|
36
|
+
internal object OneKeyImageStartupPrewarm {
|
|
37
|
+
internal data class StartupEntry(
|
|
38
|
+
val keyHash: String,
|
|
39
|
+
val diskFile: String,
|
|
40
|
+
val rawDiskFile: String? = null,
|
|
41
|
+
val width: Int,
|
|
42
|
+
val height: Int,
|
|
43
|
+
val round: Boolean = false,
|
|
44
|
+
val launch: Int = 0,
|
|
45
|
+
) {
|
|
46
|
+
val identity: String
|
|
47
|
+
get() = "$keyHash|$width|$height|$round"
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
internal data class PrewarmMetrics(
|
|
51
|
+
val entryCount: Int = 0,
|
|
52
|
+
val decodedCount: Int = 0,
|
|
53
|
+
val durationMs: Double = 0.0,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
private const val MAX_ENTRIES = 48
|
|
57
|
+
private const val RECORD_DURATION_MS = 6_000L
|
|
58
|
+
private const val MAX_DURATION_MS = 60_000L
|
|
59
|
+
private const val MIN_SETTLED_COUNT = 2
|
|
60
|
+
private const val MAX_DATA_URL_LENGTH = 65_536
|
|
61
|
+
private const val MAX_LAUNCH_AGE = 3
|
|
62
|
+
private const val MAX_MEMORY_ENTRIES = 64
|
|
63
|
+
private const val MAX_MEMORY_BYTES = 16L * 1024L * 1024L
|
|
64
|
+
internal const val MAX_FALLBACK_DISK_FILES = MAX_ENTRIES
|
|
65
|
+
internal const val MAX_FALLBACK_DISK_BYTES =
|
|
66
|
+
MAX_ENTRIES.toLong() * OneKeyMainThreadDecode.MAX_ENCODED_BYTES.toLong()
|
|
67
|
+
private const val FILE_NAME = "onekey-image-startup-v1.json"
|
|
68
|
+
internal const val GLIDE_DISK_CACHE_DIR = "image_manager_disk_cache"
|
|
69
|
+
internal const val FALLBACK_DISK_CACHE_DIR = "onekey-image-startup-disk-v1"
|
|
70
|
+
|
|
71
|
+
private val stateLock = Any()
|
|
72
|
+
private val memoryLock = Any()
|
|
73
|
+
private val diskIoLock = Any()
|
|
74
|
+
private val recorded = ArrayList<StartupEntry>()
|
|
75
|
+
private val recordedKeys = HashSet<String>()
|
|
76
|
+
private val activeStartupDiskFiles = HashSet<String>()
|
|
77
|
+
private val pendingFallbackSources = HashMap<String, String>()
|
|
78
|
+
private var recordStartTimeMs: Long? = null
|
|
79
|
+
private var recordingClosed = false
|
|
80
|
+
private var flushScheduled = false
|
|
81
|
+
private var diskClearGeneration = 0L
|
|
82
|
+
private var debounceFuture: ScheduledFuture<*>? = null
|
|
83
|
+
private var startupFileOverride: File? = null
|
|
84
|
+
@Volatile
|
|
85
|
+
private var baseCacheDir: File? = null
|
|
86
|
+
private var lastPrewarmMetrics = PrewarmMetrics()
|
|
87
|
+
|
|
88
|
+
private val memoryCache = LinkedHashMap<String, Bitmap>(MAX_MEMORY_ENTRIES, 0.75f, true)
|
|
89
|
+
private var memoryCacheBytes = 0L
|
|
90
|
+
|
|
91
|
+
private val scheduler = Executors.newSingleThreadScheduledExecutor { runnable ->
|
|
92
|
+
Thread(runnable, "onekey-image-startup-record").apply { isDaemon = true }
|
|
93
|
+
}
|
|
94
|
+
private val prewarmExecutor = Executors.newSingleThreadExecutor { runnable ->
|
|
95
|
+
Thread(runnable, "onekey-image-startup-prewarm").apply { isDaemon = true }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
@Volatile
|
|
99
|
+
internal var bitmapDecoderOverrideForTesting:
|
|
100
|
+
((ByteArray, Int, Int, Int, Int, Boolean) -> Bitmap?)? = null
|
|
101
|
+
|
|
102
|
+
@Volatile
|
|
103
|
+
internal var bitmapByteCountOverrideForTesting: ((Bitmap) -> Long)? = null
|
|
104
|
+
|
|
105
|
+
internal fun setCacheDirIfNeeded(cacheDir: File?) {
|
|
106
|
+
if (cacheDir != null && baseCacheDir == null) {
|
|
107
|
+
baseCacheDir = cacheDir
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
internal fun currentCacheDir(context: Context? = null): File? =
|
|
112
|
+
startupFileOverride?.parentFile ?: context?.applicationContext?.cacheDir ?: baseCacheDir
|
|
113
|
+
|
|
114
|
+
fun metricsSnapshot(): PrewarmMetrics = synchronized(stateLock) { lastPrewarmMetrics }
|
|
115
|
+
|
|
116
|
+
internal fun currentDiskClearGenerationForTesting(): Long = synchronized(stateLock) { diskClearGeneration }
|
|
117
|
+
|
|
118
|
+
fun keyHash(requestUrl: String, width: Int, height: Int, round: Boolean): String =
|
|
119
|
+
sha256Hex("$requestUrl|$width|$height|$round".toByteArray(Charsets.UTF_8))
|
|
120
|
+
|
|
121
|
+
fun glideDataSafeKey(uri: String): String? {
|
|
122
|
+
if (uri.isBlank()) return null
|
|
123
|
+
val sourceKey: Key = when {
|
|
124
|
+
OneKeyBlockieAvatar.isAvatarUri(uri) ->
|
|
125
|
+
OneKeyImageSafetyVersionedKey(ObjectKey(OneKeyBlockieAvatarModel(uri)))
|
|
126
|
+
uri.startsWith("data:") ->
|
|
127
|
+
OneKeyImageSafetyVersionedKey(ObjectKey(OneKeyImageDataUriModel(uri)))
|
|
128
|
+
uri.startsWith("http://") || uri.startsWith("https://") ->
|
|
129
|
+
OneKeyImageSafetyVersionedKey(OneKeyImageRemoteSourceKey(uri, null))
|
|
130
|
+
uri.startsWith("file://") ->
|
|
131
|
+
OneKeyImageSafetyVersionedKey(ObjectKey(uri))
|
|
132
|
+
else -> return null
|
|
133
|
+
}
|
|
134
|
+
val digest = MessageDigest.getInstance("SHA-256")
|
|
135
|
+
sourceKey.updateDiskCacheKey(digest)
|
|
136
|
+
return digest.digest().joinToString("") { "%02x".format(Locale.ROOT, it.toInt() and 0xff) }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
internal fun findDiskCacheFile(cacheDir: File, diskFile: String): File? {
|
|
140
|
+
if (!isSafeToken(diskFile)) return null
|
|
141
|
+
val glideFile = File(File(cacheDir, GLIDE_DISK_CACHE_DIR), "$diskFile.0")
|
|
142
|
+
if (glideFile.isFile) return glideFile
|
|
143
|
+
val fallbackFile = File(File(cacheDir, FALLBACK_DISK_CACHE_DIR), diskFile)
|
|
144
|
+
if (fallbackFile.isFile) return fallbackFile
|
|
145
|
+
return null
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
internal fun ensureFallbackDiskBytesAsync(cacheDir: File, uri: String, bytes: ByteArray) {
|
|
149
|
+
val safeKey = glideDataSafeKey(uri) ?: return
|
|
150
|
+
val expectedGeneration = synchronized(stateLock) {
|
|
151
|
+
if (recordingClosed && !activeStartupDiskFiles.contains(safeKey)) {
|
|
152
|
+
return
|
|
153
|
+
}
|
|
154
|
+
if (!recordingClosed && recorded.size >= MAX_ENTRIES && !activeStartupDiskFiles.contains(safeKey)) {
|
|
155
|
+
return
|
|
156
|
+
}
|
|
157
|
+
diskClearGeneration
|
|
158
|
+
}
|
|
159
|
+
if (findDiskCacheFile(cacheDir, safeKey) != null) return
|
|
160
|
+
scheduler.execute {
|
|
161
|
+
writeFallbackDiskBytes(cacheDir, safeKey, bytes, expectedGeneration)
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
internal fun writeFallbackDiskBytes(
|
|
166
|
+
cacheDir: File,
|
|
167
|
+
safeKey: String,
|
|
168
|
+
bytes: ByteArray,
|
|
169
|
+
expectedGeneration: Long = synchronized(stateLock) { diskClearGeneration },
|
|
170
|
+
) {
|
|
171
|
+
if (
|
|
172
|
+
!isSafeToken(safeKey) ||
|
|
173
|
+
bytes.isEmpty() ||
|
|
174
|
+
bytes.size.toLong() > MAX_FALLBACK_DISK_BYTES
|
|
175
|
+
) {
|
|
176
|
+
return
|
|
177
|
+
}
|
|
178
|
+
synchronized(diskIoLock) {
|
|
179
|
+
val allowed = synchronized(stateLock) {
|
|
180
|
+
if (diskClearGeneration != expectedGeneration) {
|
|
181
|
+
false
|
|
182
|
+
} else if (recordingClosed) {
|
|
183
|
+
activeStartupDiskFiles.contains(safeKey)
|
|
184
|
+
} else {
|
|
185
|
+
recorded.size < MAX_ENTRIES || activeStartupDiskFiles.contains(safeKey)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (!allowed) return
|
|
189
|
+
try {
|
|
190
|
+
val dir = File(cacheDir, FALLBACK_DISK_CACHE_DIR)
|
|
191
|
+
if (!dir.exists()) dir.mkdirs()
|
|
192
|
+
val target = File(dir, safeKey)
|
|
193
|
+
if (!target.isFile || target.length() != bytes.size.toLong()) {
|
|
194
|
+
val tmp = File(dir, "$safeKey.tmp")
|
|
195
|
+
tmp.writeBytes(bytes)
|
|
196
|
+
if (!tmp.renameTo(target)) {
|
|
197
|
+
tmp.copyTo(target, overwrite = true)
|
|
198
|
+
tmp.delete()
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
trimFallbackDiskCacheLocked(dir, protectedKey = safeKey)
|
|
202
|
+
} catch (_: Exception) {
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
private fun trimFallbackDiskCacheLocked(dir: File, protectedKey: String? = null) {
|
|
208
|
+
val files = dir.listFiles() ?: return
|
|
209
|
+
val regularFiles = ArrayList<File>(files.size)
|
|
210
|
+
for (candidate in files) {
|
|
211
|
+
if (!candidate.isFile) continue
|
|
212
|
+
if (candidate.name.endsWith(".tmp")) {
|
|
213
|
+
candidate.delete()
|
|
214
|
+
continue
|
|
215
|
+
}
|
|
216
|
+
regularFiles.add(candidate)
|
|
217
|
+
}
|
|
218
|
+
var totalBytes = regularFiles.sumOf { it.length().coerceAtLeast(0L) }
|
|
219
|
+
if (regularFiles.size <= MAX_FALLBACK_DISK_FILES && totalBytes <= MAX_FALLBACK_DISK_BYTES) {
|
|
220
|
+
return
|
|
221
|
+
}
|
|
222
|
+
val activeSnapshot = synchronized(stateLock) { HashSet(activeStartupDiskFiles) }
|
|
223
|
+
val evictionOrder = regularFiles
|
|
224
|
+
.filter { it.name != protectedKey }
|
|
225
|
+
.sortedWith(
|
|
226
|
+
compareBy<File>(
|
|
227
|
+
{ activeSnapshot.contains(it.name) },
|
|
228
|
+
{ it.lastModified() },
|
|
229
|
+
{ it.name },
|
|
230
|
+
),
|
|
231
|
+
)
|
|
232
|
+
var remainingCount = regularFiles.size
|
|
233
|
+
for (victim in evictionOrder) {
|
|
234
|
+
if (remainingCount <= MAX_FALLBACK_DISK_FILES && totalBytes <= MAX_FALLBACK_DISK_BYTES) {
|
|
235
|
+
break
|
|
236
|
+
}
|
|
237
|
+
val len = victim.length().coerceAtLeast(0L)
|
|
238
|
+
if (victim.delete()) {
|
|
239
|
+
remainingCount -= 1
|
|
240
|
+
totalBytes = (totalBytes - len).coerceAtLeast(0L)
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
fun cachedBitmap(keyHash: String): Bitmap? = synchronized(memoryLock) {
|
|
246
|
+
memoryCache[keyHash]
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
fun cachedBitmap(
|
|
250
|
+
requestUrl: String,
|
|
251
|
+
width: Int,
|
|
252
|
+
height: Int,
|
|
253
|
+
round: Boolean,
|
|
254
|
+
headersJson: String? = null,
|
|
255
|
+
): Bitmap? {
|
|
256
|
+
if (OneKeyImageModel.headers(headersJson).isNotEmpty()) return null
|
|
257
|
+
return cachedBitmap(keyHash(requestUrl, width, height, round))
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
fun putMemoryBitmap(keyHash: String, bitmap: Bitmap) {
|
|
261
|
+
val bytes = estimateBitmapBytes(bitmap)
|
|
262
|
+
if (bytes > MAX_MEMORY_BYTES) return
|
|
263
|
+
synchronized(memoryLock) {
|
|
264
|
+
memoryCache.put(keyHash, bitmap)?.let { previous ->
|
|
265
|
+
memoryCacheBytes = (memoryCacheBytes - estimateBitmapBytes(previous)).coerceAtLeast(0L)
|
|
266
|
+
}
|
|
267
|
+
memoryCacheBytes += bytes
|
|
268
|
+
while (memoryCache.size > MAX_MEMORY_ENTRIES || memoryCacheBytes > MAX_MEMORY_BYTES) {
|
|
269
|
+
val eldest = memoryCache.entries.firstOrNull() ?: break
|
|
270
|
+
memoryCacheBytes = (memoryCacheBytes - estimateBitmapBytes(eldest.value)).coerceAtLeast(0L)
|
|
271
|
+
memoryCache.remove(eldest.key)
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
fun clearMemoryCache() {
|
|
277
|
+
synchronized(memoryLock) {
|
|
278
|
+
memoryCache.clear()
|
|
279
|
+
memoryCacheBytes = 0L
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
fun clearDiskCache(cacheDir: File? = currentCacheDir()) {
|
|
284
|
+
val file: File?
|
|
285
|
+
val resolvedDir: File?
|
|
286
|
+
synchronized(stateLock) {
|
|
287
|
+
diskClearGeneration += 1L
|
|
288
|
+
debounceFuture?.cancel(false)
|
|
289
|
+
debounceFuture = null
|
|
290
|
+
flushScheduled = false
|
|
291
|
+
recorded.clear()
|
|
292
|
+
recordedKeys.clear()
|
|
293
|
+
activeStartupDiskFiles.clear()
|
|
294
|
+
pendingFallbackSources.clear()
|
|
295
|
+
file = startupFile()
|
|
296
|
+
resolvedDir = cacheDir ?: baseCacheDir ?: file?.parentFile
|
|
297
|
+
}
|
|
298
|
+
synchronized(diskIoLock) {
|
|
299
|
+
try {
|
|
300
|
+
file?.delete()
|
|
301
|
+
file?.parentFile?.let { File(it, "${file.name}.tmp").delete() }
|
|
302
|
+
} catch (_: Exception) {
|
|
303
|
+
}
|
|
304
|
+
try {
|
|
305
|
+
if (resolvedDir != null) {
|
|
306
|
+
File(resolvedDir, FALLBACK_DISK_CACHE_DIR).deleteRecursively()
|
|
307
|
+
}
|
|
308
|
+
} catch (_: Exception) {
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
private fun estimateBitmapBytes(bitmap: Bitmap): Long {
|
|
314
|
+
bitmapByteCountOverrideForTesting?.let { return it(bitmap) }
|
|
315
|
+
return try {
|
|
316
|
+
val count = bitmap.allocationByteCount.toLong()
|
|
317
|
+
if (count > 0L) count else (bitmap.width.toLong() * bitmap.height.toLong() * 4L).coerceAtLeast(1L)
|
|
318
|
+
} catch (_: Throwable) {
|
|
319
|
+
4096L
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
fun note(
|
|
324
|
+
cacheDir: File?,
|
|
325
|
+
requestUrl: String,
|
|
326
|
+
rawUrl: String,
|
|
327
|
+
headersJson: String?,
|
|
328
|
+
cachePolicy: OneKeyImageCachePolicy?,
|
|
329
|
+
width: Int,
|
|
330
|
+
height: Int,
|
|
331
|
+
round: Boolean,
|
|
332
|
+
) {
|
|
333
|
+
if (cacheDir != null) setCacheDirIfNeeded(cacheDir)
|
|
334
|
+
val policy = cachePolicy ?: OneKeyImageCachePolicy.MEMORY_DISK
|
|
335
|
+
if (policy != OneKeyImageCachePolicy.MEMORY_DISK) return
|
|
336
|
+
if (OneKeyImageModel.headers(headersJson).isNotEmpty()) return
|
|
337
|
+
if (width <= 0 || height <= 0) return
|
|
338
|
+
if (!isSupportedStartupUri(requestUrl) || !isSupportedStartupUri(rawUrl)) return
|
|
339
|
+
if (requestUrl.startsWith("data:") && requestUrl.length > MAX_DATA_URL_LENGTH) return
|
|
340
|
+
if (rawUrl.startsWith("data:") && rawUrl.length > MAX_DATA_URL_LENGTH) return
|
|
341
|
+
|
|
342
|
+
val entryKeyHash = keyHash(requestUrl, width, height, round)
|
|
343
|
+
val diskFile = glideDataSafeKey(requestUrl) ?: return
|
|
344
|
+
val rawDiskFile = if (requestUrl != rawUrl) glideDataSafeKey(rawUrl) else null
|
|
345
|
+
val entry = StartupEntry(
|
|
346
|
+
keyHash = entryKeyHash,
|
|
347
|
+
diskFile = diskFile,
|
|
348
|
+
rawDiskFile = rawDiskFile,
|
|
349
|
+
width = width,
|
|
350
|
+
height = height,
|
|
351
|
+
round = round,
|
|
352
|
+
launch = 0,
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
val now = System.currentTimeMillis()
|
|
356
|
+
synchronized(stateLock) {
|
|
357
|
+
if (recordingClosed) return
|
|
358
|
+
val start = recordStartTimeMs ?: now.also { recordStartTimeMs = it }
|
|
359
|
+
if (now - start >= MAX_DURATION_MS && recorded.isNotEmpty()) {
|
|
360
|
+
recordingClosed = true
|
|
361
|
+
schedulePersistLocked(delayMs = 0L)
|
|
362
|
+
return
|
|
363
|
+
}
|
|
364
|
+
var accepted = false
|
|
365
|
+
if (recorded.size < MAX_ENTRIES && recordedKeys.add(entry.identity)) {
|
|
366
|
+
recorded.add(entry)
|
|
367
|
+
activeStartupDiskFiles.add(diskFile)
|
|
368
|
+
rawDiskFile?.let { activeStartupDiskFiles.add(it) }
|
|
369
|
+
accepted = true
|
|
370
|
+
} else if (activeStartupDiskFiles.contains(diskFile)) {
|
|
371
|
+
accepted = true
|
|
372
|
+
}
|
|
373
|
+
if (
|
|
374
|
+
accepted &&
|
|
375
|
+
(requestUrl.startsWith("file://") || requestUrl.startsWith("data:") || OneKeyBlockieAvatar.isAvatarUri(requestUrl))
|
|
376
|
+
) {
|
|
377
|
+
pendingFallbackSources.putIfAbsent(diskFile, requestUrl)
|
|
378
|
+
}
|
|
379
|
+
schedulePersistLocked(delayMs = RECORD_DURATION_MS)
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
private fun isSupportedStartupUri(uri: String): Boolean =
|
|
384
|
+
uri.startsWith("http://") ||
|
|
385
|
+
uri.startsWith("https://") ||
|
|
386
|
+
OneKeyBlockieAvatar.isAvatarUri(uri) ||
|
|
387
|
+
uri.startsWith("file://") ||
|
|
388
|
+
uri.startsWith("data:")
|
|
389
|
+
|
|
390
|
+
private fun schedulePersistLocked(delayMs: Long) {
|
|
391
|
+
debounceFuture?.cancel(false)
|
|
392
|
+
flushScheduled = true
|
|
393
|
+
debounceFuture = scheduler.schedule({
|
|
394
|
+
debounceFired()
|
|
395
|
+
}, delayMs, TimeUnit.MILLISECONDS)
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
private fun debounceFired() {
|
|
399
|
+
val entries: List<StartupEntry>
|
|
400
|
+
val fallbackMap: Map<String, String>
|
|
401
|
+
val file: File?
|
|
402
|
+
val cacheDir: File?
|
|
403
|
+
val expectedGeneration: Long
|
|
404
|
+
val now = System.currentTimeMillis()
|
|
405
|
+
synchronized(stateLock) {
|
|
406
|
+
if (recordingClosed && !flushScheduled) return
|
|
407
|
+
val start = recordStartTimeMs ?: now
|
|
408
|
+
if (
|
|
409
|
+
!recordingClosed &&
|
|
410
|
+
recorded.size < MIN_SETTLED_COUNT &&
|
|
411
|
+
now - start < MAX_DURATION_MS
|
|
412
|
+
) {
|
|
413
|
+
schedulePersistLocked(delayMs = RECORD_DURATION_MS)
|
|
414
|
+
return
|
|
415
|
+
}
|
|
416
|
+
recordingClosed = true
|
|
417
|
+
flushScheduled = false
|
|
418
|
+
debounceFuture = null
|
|
419
|
+
entries = ArrayList(recorded)
|
|
420
|
+
fallbackMap = HashMap(pendingFallbackSources)
|
|
421
|
+
pendingFallbackSources.clear()
|
|
422
|
+
file = startupFile()
|
|
423
|
+
cacheDir = currentCacheDir()
|
|
424
|
+
expectedGeneration = diskClearGeneration
|
|
425
|
+
}
|
|
426
|
+
if (cacheDir != null && fallbackMap.isNotEmpty()) {
|
|
427
|
+
materializeFallbackSources(cacheDir, fallbackMap, expectedGeneration)
|
|
428
|
+
}
|
|
429
|
+
if (file != null) {
|
|
430
|
+
persist(entries, file, expectedGeneration)
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
private fun materializeFallbackSources(
|
|
435
|
+
cacheDir: File,
|
|
436
|
+
sources: Map<String, String>,
|
|
437
|
+
expectedGeneration: Long = synchronized(stateLock) { diskClearGeneration },
|
|
438
|
+
) {
|
|
439
|
+
for ((diskFile, uri) in sources) {
|
|
440
|
+
if (synchronized(stateLock) { diskClearGeneration != expectedGeneration }) return
|
|
441
|
+
if (findDiskCacheFile(cacheDir, diskFile) != null) continue
|
|
442
|
+
val bytes = try {
|
|
443
|
+
when {
|
|
444
|
+
uri.startsWith("file://") -> {
|
|
445
|
+
val rawPath = uri.removePrefix("file://").substringBefore('?').substringBefore('#')
|
|
446
|
+
val f = File(rawPath)
|
|
447
|
+
if (f.isFile && f.length() in 1L..MAX_FALLBACK_DISK_BYTES) f.readBytes() else null
|
|
448
|
+
}
|
|
449
|
+
uri.startsWith("data:") -> {
|
|
450
|
+
val comma = uri.indexOf(',')
|
|
451
|
+
if (comma > 0 && uri.substring(0, comma).lowercase(Locale.ROOT).contains(";base64")) {
|
|
452
|
+
val payloadStart = comma + 1
|
|
453
|
+
val count = OneKeyImageSafety.dataUriDecodedByteCount(uri, payloadStart)
|
|
454
|
+
if (count in 1L..minOf(MAX_FALLBACK_DISK_BYTES, OneKeyImageSafety.MAX_DATA_URI_DECODED_BYTES)) {
|
|
455
|
+
OneKeyImageSafety.decodeDataUriBase64(uri.substring(payloadStart))
|
|
456
|
+
} else null
|
|
457
|
+
} else null
|
|
458
|
+
}
|
|
459
|
+
OneKeyBlockieAvatar.isAvatarUri(uri) -> OneKeyBlockieAvatar.png(uri)
|
|
460
|
+
else -> null
|
|
461
|
+
}
|
|
462
|
+
} catch (_: Exception) {
|
|
463
|
+
null
|
|
464
|
+
}
|
|
465
|
+
if (bytes != null && bytes.isNotEmpty()) {
|
|
466
|
+
writeFallbackDiskBytes(cacheDir, diskFile, bytes, expectedGeneration)
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
private fun startupFile(): File? {
|
|
472
|
+
startupFileOverride?.let { return it }
|
|
473
|
+
val dir = baseCacheDir ?: return null
|
|
474
|
+
return File(dir, FILE_NAME)
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
private fun persist(
|
|
478
|
+
entries: List<StartupEntry>,
|
|
479
|
+
file: File,
|
|
480
|
+
expectedGeneration: Long = synchronized(stateLock) { diskClearGeneration },
|
|
481
|
+
) {
|
|
482
|
+
if (entries.isEmpty()) {
|
|
483
|
+
synchronized(diskIoLock) {
|
|
484
|
+
if (synchronized(stateLock) { diskClearGeneration != expectedGeneration }) return
|
|
485
|
+
val existing = readEntries(file)
|
|
486
|
+
val activeFiles = HashSet<String>(existing.size * 2)
|
|
487
|
+
for (entry in existing) {
|
|
488
|
+
activeFiles.add(entry.diskFile)
|
|
489
|
+
entry.rawDiskFile?.let { activeFiles.add(it) }
|
|
490
|
+
}
|
|
491
|
+
synchronized(stateLock) {
|
|
492
|
+
if (diskClearGeneration == expectedGeneration) {
|
|
493
|
+
activeStartupDiskFiles.clear()
|
|
494
|
+
activeStartupDiskFiles.addAll(activeFiles)
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
file.parentFile?.let { parent ->
|
|
498
|
+
pruneFallbackDiskCacheLocked(File(parent, FALLBACK_DISK_CACHE_DIR), activeFiles)
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
return
|
|
502
|
+
}
|
|
503
|
+
synchronized(diskIoLock) {
|
|
504
|
+
if (synchronized(stateLock) { diskClearGeneration != expectedGeneration }) return
|
|
505
|
+
val existing = readEntries(file)
|
|
506
|
+
val maxExistingLaunch = existing.maxOfOrNull { it.launch } ?: 0
|
|
507
|
+
val currentLaunch = maxExistingLaunch + 1
|
|
508
|
+
|
|
509
|
+
val stampedCurrent = entries.map {
|
|
510
|
+
StartupEntry(
|
|
511
|
+
keyHash = it.keyHash,
|
|
512
|
+
diskFile = it.diskFile,
|
|
513
|
+
rawDiskFile = it.rawDiskFile,
|
|
514
|
+
width = it.width,
|
|
515
|
+
height = it.height,
|
|
516
|
+
round = it.round,
|
|
517
|
+
launch = currentLaunch,
|
|
518
|
+
)
|
|
519
|
+
}
|
|
520
|
+
val seen = stampedCurrent.mapTo(HashSet()) { it.identity }
|
|
521
|
+
val merged = ArrayList<StartupEntry>(MAX_ENTRIES)
|
|
522
|
+
merged.addAll(stampedCurrent.take(MAX_ENTRIES))
|
|
523
|
+
|
|
524
|
+
for (entry in existing) {
|
|
525
|
+
if (merged.size >= MAX_ENTRIES) break
|
|
526
|
+
if (!isValidEntry(entry)) continue
|
|
527
|
+
val age = currentLaunch - entry.launch
|
|
528
|
+
if (age >= MAX_LAUNCH_AGE) continue
|
|
529
|
+
if (seen.add(entry.identity)) {
|
|
530
|
+
merged.add(entry)
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
val activeFiles = HashSet<String>(merged.size * 2)
|
|
535
|
+
for (entry in merged) {
|
|
536
|
+
activeFiles.add(entry.diskFile)
|
|
537
|
+
entry.rawDiskFile?.let { activeFiles.add(it) }
|
|
538
|
+
}
|
|
539
|
+
synchronized(stateLock) {
|
|
540
|
+
if (diskClearGeneration == expectedGeneration) {
|
|
541
|
+
activeStartupDiskFiles.clear()
|
|
542
|
+
activeStartupDiskFiles.addAll(activeFiles)
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
val unchanged =
|
|
547
|
+
existing.size == merged.size &&
|
|
548
|
+
existing.indices.all { i ->
|
|
549
|
+
existing[i].identity == merged[i].identity &&
|
|
550
|
+
existing[i].diskFile == merged[i].diskFile &&
|
|
551
|
+
existing[i].rawDiskFile == merged[i].rawDiskFile &&
|
|
552
|
+
(currentLaunch - existing[i].launch) < 1
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
try {
|
|
556
|
+
if (!unchanged) {
|
|
557
|
+
file.parentFile?.mkdirs()
|
|
558
|
+
val json = encodeEntriesJson(merged)
|
|
559
|
+
val tmp = File(file.parentFile, "${file.name}.tmp")
|
|
560
|
+
tmp.writeText(json, Charsets.UTF_8)
|
|
561
|
+
if (!tmp.renameTo(file)) {
|
|
562
|
+
tmp.copyTo(file, overwrite = true)
|
|
563
|
+
tmp.delete()
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
file.parentFile?.let { parent ->
|
|
567
|
+
pruneFallbackDiskCacheLocked(File(parent, FALLBACK_DISK_CACHE_DIR), activeFiles)
|
|
568
|
+
}
|
|
569
|
+
} catch (_: Exception) {
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
private fun pruneFallbackDiskCacheLocked(fallbackDir: File, activeFiles: Set<String>) {
|
|
575
|
+
if (!fallbackDir.isDirectory) return
|
|
576
|
+
fallbackDir.listFiles()?.forEach { candidate ->
|
|
577
|
+
if (candidate.isFile && !activeFiles.contains(candidate.name)) {
|
|
578
|
+
candidate.delete()
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
trimFallbackDiskCacheLocked(fallbackDir, protectedKey = null)
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
fun startPrewarmAsync(context: Context) {
|
|
585
|
+
val appContext = context.applicationContext ?: context
|
|
586
|
+
setCacheDirIfNeeded(appContext.cacheDir)
|
|
587
|
+
prewarmExecutor.execute {
|
|
588
|
+
prewarmStartupSet(appContext.cacheDir)
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
fun prewarmStartupSet(cacheDir: File? = currentCacheDir()) {
|
|
593
|
+
val startNs = System.nanoTime()
|
|
594
|
+
if (cacheDir != null) setCacheDirIfNeeded(cacheDir)
|
|
595
|
+
val file = synchronized(stateLock) { startupFile() } ?: return
|
|
596
|
+
val resolvedCacheDir = cacheDir ?: file.parentFile ?: return
|
|
597
|
+
val entries = readEntries(file)
|
|
598
|
+
.filter { isValidEntry(it) }
|
|
599
|
+
.take(MAX_ENTRIES)
|
|
600
|
+
if (entries.isEmpty()) {
|
|
601
|
+
val elapsedMs = (System.nanoTime() - startNs) / 1_000_000.0
|
|
602
|
+
synchronized(stateLock) {
|
|
603
|
+
lastPrewarmMetrics = PrewarmMetrics(0, 0, elapsedMs)
|
|
604
|
+
}
|
|
605
|
+
return
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
var decodedCount = 0
|
|
609
|
+
for (entry in entries) {
|
|
610
|
+
if (cachedBitmap(entry.keyHash) != null) {
|
|
611
|
+
decodedCount += 1
|
|
612
|
+
continue
|
|
613
|
+
}
|
|
614
|
+
val bytes = loadCachedDiskBytes(resolvedCacheDir, entry) ?: continue
|
|
615
|
+
val metadata = try {
|
|
616
|
+
OneKeyEncodedImageInspector.inspect(ByteArrayInputStream(bytes))
|
|
617
|
+
} catch (_: Exception) {
|
|
618
|
+
continue
|
|
619
|
+
}
|
|
620
|
+
if (metadata.animated) continue
|
|
621
|
+
val bounds = if (metadata.width > 0 && metadata.height > 0) {
|
|
622
|
+
metadata.width to metadata.height
|
|
623
|
+
} else {
|
|
624
|
+
OneKeyMainThreadDecode.extractStaticImageBounds(bytes)
|
|
625
|
+
} ?: continue
|
|
626
|
+
try {
|
|
627
|
+
OneKeyImageSafety.requireStaticDimensions(bounds.first, bounds.second)
|
|
628
|
+
} catch (_: Exception) {
|
|
629
|
+
continue
|
|
630
|
+
}
|
|
631
|
+
val bitmap = decodeStaticBitmap(
|
|
632
|
+
bytes = bytes,
|
|
633
|
+
sourceWidth = bounds.first,
|
|
634
|
+
sourceHeight = bounds.second,
|
|
635
|
+
targetWidth = entry.width,
|
|
636
|
+
targetHeight = entry.height,
|
|
637
|
+
round = entry.round,
|
|
638
|
+
) ?: continue
|
|
639
|
+
putMemoryBitmap(entry.keyHash, bitmap)
|
|
640
|
+
decodedCount += 1
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
val totalMs = (System.nanoTime() - startNs) / 1_000_000.0
|
|
644
|
+
synchronized(stateLock) {
|
|
645
|
+
lastPrewarmMetrics = PrewarmMetrics(
|
|
646
|
+
entryCount = entries.size,
|
|
647
|
+
decodedCount = decodedCount,
|
|
648
|
+
durationMs = totalMs,
|
|
649
|
+
)
|
|
650
|
+
}
|
|
651
|
+
try {
|
|
652
|
+
Log.i(
|
|
653
|
+
"OneKeyImage",
|
|
654
|
+
String.format(
|
|
655
|
+
Locale.ROOT,
|
|
656
|
+
"[OneKeyImageStartupMetrics] imagePrewarm entries=%d decoded=%d totalMs=%.3f",
|
|
657
|
+
entries.size,
|
|
658
|
+
decodedCount,
|
|
659
|
+
totalMs,
|
|
660
|
+
),
|
|
661
|
+
)
|
|
662
|
+
} catch (_: Throwable) {
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
private fun loadCachedDiskBytes(cacheDir: File, entry: StartupEntry): ByteArray? {
|
|
667
|
+
val candidates = if (!entry.rawDiskFile.isNullOrEmpty() && entry.rawDiskFile != entry.diskFile) {
|
|
668
|
+
listOf(entry.diskFile, entry.rawDiskFile)
|
|
669
|
+
} else {
|
|
670
|
+
listOf(entry.diskFile)
|
|
671
|
+
}
|
|
672
|
+
for (token in candidates) {
|
|
673
|
+
val file = findDiskCacheFile(cacheDir, token) ?: continue
|
|
674
|
+
val length = file.length()
|
|
675
|
+
if (length <= 0L || length > OneKeyImageSafety.MAX_ENCODED_BYTES) continue
|
|
676
|
+
val bytes = try {
|
|
677
|
+
file.readBytes()
|
|
678
|
+
} catch (_: Exception) {
|
|
679
|
+
continue
|
|
680
|
+
}
|
|
681
|
+
if (bytes.isNotEmpty() && bytes.size <= OneKeyImageSafety.MAX_ENCODED_BYTES) {
|
|
682
|
+
return bytes
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
return null
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
internal fun defaultBitmapDensity(): Int = try {
|
|
689
|
+
Resources.getSystem().displayMetrics.densityDpi.takeIf { it > 0 }
|
|
690
|
+
?: DisplayMetrics.DENSITY_DEFAULT
|
|
691
|
+
} catch (_: Throwable) {
|
|
692
|
+
DisplayMetrics.DENSITY_DEFAULT
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
internal fun exifOrientationSwapsDimensions(orientation: Int): Boolean =
|
|
696
|
+
orientation in 5..8
|
|
697
|
+
|
|
698
|
+
internal fun decodeStaticBitmap(
|
|
699
|
+
bytes: ByteArray,
|
|
700
|
+
sourceWidth: Int,
|
|
701
|
+
sourceHeight: Int,
|
|
702
|
+
targetWidth: Int,
|
|
703
|
+
targetHeight: Int,
|
|
704
|
+
round: Boolean,
|
|
705
|
+
): Bitmap? {
|
|
706
|
+
val safeTarget = OneKeyImageDecodeDimensions.forRender(targetWidth, targetHeight)
|
|
707
|
+
val exifOrientation = extractExifOrientation(bytes)
|
|
708
|
+
val swapsDimensions = exifOrientationSwapsDimensions(exifOrientation)
|
|
709
|
+
val orientedSourceWidth = if (swapsDimensions) sourceHeight else sourceWidth
|
|
710
|
+
val orientedSourceHeight = if (swapsDimensions) sourceWidth else sourceHeight
|
|
711
|
+
bitmapDecoderOverrideForTesting?.let { override ->
|
|
712
|
+
return override(
|
|
713
|
+
bytes,
|
|
714
|
+
orientedSourceWidth,
|
|
715
|
+
orientedSourceHeight,
|
|
716
|
+
safeTarget.width,
|
|
717
|
+
safeTarget.height,
|
|
718
|
+
round,
|
|
719
|
+
)
|
|
720
|
+
}
|
|
721
|
+
return try {
|
|
722
|
+
val scaleFactor = OneKeyImageDecodeDimensions.safeStaticScaleFactor(
|
|
723
|
+
sourceWidth = orientedSourceWidth,
|
|
724
|
+
sourceHeight = orientedSourceHeight,
|
|
725
|
+
requestedWidth = safeTarget.width,
|
|
726
|
+
requestedHeight = safeTarget.height,
|
|
727
|
+
)
|
|
728
|
+
val options = BitmapFactory.Options().apply {
|
|
729
|
+
inPreferredConfig = Bitmap.Config.ARGB_8888
|
|
730
|
+
if (scaleFactor < 1f) {
|
|
731
|
+
inScaled = true
|
|
732
|
+
inDensity = 10_000
|
|
733
|
+
inTargetDensity = (scaleFactor * 10_000f).toInt().coerceAtLeast(1)
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
val targetDensity = defaultBitmapDensity()
|
|
737
|
+
var decoded = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) ?: return null
|
|
738
|
+
decoded.density = targetDensity
|
|
739
|
+
if (decoded.width <= 0 || decoded.height <= 0) return null
|
|
740
|
+
if (decoded.allocationByteCount.toLong() > OneKeyImageDecodeDimensions.MAX_DECODE_BYTES) {
|
|
741
|
+
val targetW = floor(sourceWidth * scaleFactor).toInt().coerceAtLeast(1)
|
|
742
|
+
val targetH = floor(sourceHeight * scaleFactor).toInt().coerceAtLeast(1)
|
|
743
|
+
val scaled = Bitmap.createScaledBitmap(decoded, targetW, targetH, true)
|
|
744
|
+
if (scaled !== decoded) decoded.recycle()
|
|
745
|
+
scaled.density = targetDensity
|
|
746
|
+
decoded = scaled
|
|
747
|
+
}
|
|
748
|
+
decoded = applyExifOrientation(decoded, exifOrientation, targetDensity)
|
|
749
|
+
if (decoded.allocationByteCount.toLong() > OneKeyImageDecodeDimensions.MAX_DECODE_BYTES) {
|
|
750
|
+
return null
|
|
751
|
+
}
|
|
752
|
+
if (round) circleCropBitmap(decoded) else decoded
|
|
753
|
+
} catch (_: Throwable) {
|
|
754
|
+
null
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
internal fun applyExifOrientation(
|
|
759
|
+
source: Bitmap,
|
|
760
|
+
orientation: Int,
|
|
761
|
+
targetDensity: Int = defaultBitmapDensity(),
|
|
762
|
+
): Bitmap {
|
|
763
|
+
source.density = targetDensity
|
|
764
|
+
if (orientation !in 2..8) return source
|
|
765
|
+
val matrix = Matrix().apply {
|
|
766
|
+
when (orientation) {
|
|
767
|
+
2 -> setScale(-1f, 1f)
|
|
768
|
+
3 -> setRotate(180f)
|
|
769
|
+
4 -> {
|
|
770
|
+
setRotate(180f)
|
|
771
|
+
postScale(-1f, 1f)
|
|
772
|
+
}
|
|
773
|
+
5 -> {
|
|
774
|
+
setRotate(90f)
|
|
775
|
+
postScale(-1f, 1f)
|
|
776
|
+
}
|
|
777
|
+
6 -> setRotate(90f)
|
|
778
|
+
7 -> {
|
|
779
|
+
setRotate(-90f)
|
|
780
|
+
postScale(-1f, 1f)
|
|
781
|
+
}
|
|
782
|
+
8 -> setRotate(-90f)
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
val oriented = Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true)
|
|
786
|
+
if (oriented !== source) {
|
|
787
|
+
source.recycle()
|
|
788
|
+
}
|
|
789
|
+
oriented.density = targetDensity
|
|
790
|
+
return oriented
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
internal fun circleCropBitmap(source: Bitmap): Bitmap {
|
|
794
|
+
val size = min(source.width, source.height).coerceAtLeast(1)
|
|
795
|
+
val output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
|
|
796
|
+
val targetDensity = source.density.takeIf { it > 0 } ?: defaultBitmapDensity()
|
|
797
|
+
source.density = targetDensity
|
|
798
|
+
output.density = targetDensity
|
|
799
|
+
val canvas = Canvas(output)
|
|
800
|
+
canvas.density = targetDensity
|
|
801
|
+
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
|
802
|
+
val radius = size / 2f
|
|
803
|
+
canvas.drawCircle(radius, radius, radius, paint)
|
|
804
|
+
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
|
|
805
|
+
val left = (size - source.width) / 2f
|
|
806
|
+
val top = (size - source.height) / 2f
|
|
807
|
+
canvas.drawBitmap(source, left, top, paint)
|
|
808
|
+
if (output !== source) {
|
|
809
|
+
source.recycle()
|
|
810
|
+
}
|
|
811
|
+
return output
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
internal fun extractExifOrientation(bytes: ByteArray): Int {
|
|
815
|
+
// 1. JPEG APP1 Exif segment
|
|
816
|
+
if (bytes.size >= 4 && (bytes[0].toInt() and 0xff) == 0xff && (bytes[1].toInt() and 0xff) == 0xd8) {
|
|
817
|
+
var pos = 2
|
|
818
|
+
while (pos + 4 <= bytes.size) {
|
|
819
|
+
if ((bytes[pos].toInt() and 0xff) != 0xff) {
|
|
820
|
+
pos += 1
|
|
821
|
+
continue
|
|
822
|
+
}
|
|
823
|
+
var marker = bytes[pos + 1].toInt() and 0xff
|
|
824
|
+
pos += 2
|
|
825
|
+
while (marker == 0xff && pos < bytes.size) {
|
|
826
|
+
marker = bytes[pos].toInt() and 0xff
|
|
827
|
+
pos += 1
|
|
828
|
+
}
|
|
829
|
+
if (marker == 0xd9 || marker == 0xda) break
|
|
830
|
+
if (marker == 0xd8 || marker in 0xd0..0xd7 || marker == 0x01) continue
|
|
831
|
+
if (pos + 2 > bytes.size) break
|
|
832
|
+
val segmentLength = readU16Be(bytes, pos)
|
|
833
|
+
if (segmentLength < 2 || pos + segmentLength > bytes.size) break
|
|
834
|
+
if (marker == 0xe1 && segmentLength >= 16 && hasExifHeaderPrefix(bytes, pos + 2, pos + segmentLength)) {
|
|
835
|
+
val orientation = parseTiffOrientation(bytes, pos + 8, pos + segmentLength)
|
|
836
|
+
if (orientation in 1..8) return orientation
|
|
837
|
+
}
|
|
838
|
+
pos += segmentLength
|
|
839
|
+
}
|
|
840
|
+
return 1
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
// 2. WebP RIFF EXIF chunk
|
|
844
|
+
if (
|
|
845
|
+
bytes.size >= 20 &&
|
|
846
|
+
bytes[0] == 'R'.code.toByte() &&
|
|
847
|
+
bytes[1] == 'I'.code.toByte() &&
|
|
848
|
+
bytes[2] == 'F'.code.toByte() &&
|
|
849
|
+
bytes[3] == 'F'.code.toByte() &&
|
|
850
|
+
bytes[8] == 'W'.code.toByte() &&
|
|
851
|
+
bytes[9] == 'E'.code.toByte() &&
|
|
852
|
+
bytes[10] == 'B'.code.toByte() &&
|
|
853
|
+
bytes[11] == 'P'.code.toByte()
|
|
854
|
+
) {
|
|
855
|
+
var chunkPos = 12
|
|
856
|
+
while (chunkPos <= bytes.size - 8) {
|
|
857
|
+
val chunkType = String(bytes, chunkPos, 4, Charsets.US_ASCII)
|
|
858
|
+
val chunkSize = readInt32Le(bytes, chunkPos + 4)
|
|
859
|
+
val payloadStart = chunkPos + 8
|
|
860
|
+
if (chunkSize < 0 || chunkSize > bytes.size - payloadStart) break
|
|
861
|
+
val payloadEnd = payloadStart + chunkSize
|
|
862
|
+
if (chunkType == "EXIF" && chunkSize >= 8) {
|
|
863
|
+
val tiffStart = if (hasExifHeaderPrefix(bytes, payloadStart, payloadEnd)) {
|
|
864
|
+
payloadStart + 6
|
|
865
|
+
} else {
|
|
866
|
+
payloadStart
|
|
867
|
+
}
|
|
868
|
+
val orientation = parseTiffOrientation(bytes, tiffStart, payloadEnd)
|
|
869
|
+
if (orientation in 1..8) return orientation
|
|
870
|
+
}
|
|
871
|
+
val paddedSize = chunkSize + (chunkSize and 1)
|
|
872
|
+
if (paddedSize < 0 || paddedSize > bytes.size - payloadStart) break
|
|
873
|
+
chunkPos = payloadStart + paddedSize
|
|
874
|
+
}
|
|
875
|
+
return 1
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
// 3. PNG eXIf chunk
|
|
879
|
+
if (
|
|
880
|
+
bytes.size >= 24 &&
|
|
881
|
+
bytes[0] == 0x89.toByte() &&
|
|
882
|
+
bytes[1] == 0x50.toByte() &&
|
|
883
|
+
bytes[2] == 0x4e.toByte() &&
|
|
884
|
+
bytes[3] == 0x47.toByte()
|
|
885
|
+
) {
|
|
886
|
+
var chunkPos = 8
|
|
887
|
+
while (chunkPos <= bytes.size - 12) {
|
|
888
|
+
val chunkSize = readInt32Be(bytes, chunkPos)
|
|
889
|
+
val chunkType = String(bytes, chunkPos + 4, 4, Charsets.US_ASCII)
|
|
890
|
+
val payloadStart = chunkPos + 8
|
|
891
|
+
if (chunkSize < 0 || chunkSize > bytes.size - payloadStart - 4) break
|
|
892
|
+
val payloadEnd = payloadStart + chunkSize
|
|
893
|
+
if (chunkType == "eXIf" && chunkSize >= 8) {
|
|
894
|
+
val tiffStart = if (hasExifHeaderPrefix(bytes, payloadStart, payloadEnd)) {
|
|
895
|
+
payloadStart + 6
|
|
896
|
+
} else {
|
|
897
|
+
payloadStart
|
|
898
|
+
}
|
|
899
|
+
val orientation = parseTiffOrientation(bytes, tiffStart, payloadEnd)
|
|
900
|
+
if (orientation in 1..8) return orientation
|
|
901
|
+
}
|
|
902
|
+
if (chunkType == "IEND") break
|
|
903
|
+
chunkPos = payloadEnd + 4
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
return 1
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
private fun hasExifHeaderPrefix(bytes: ByteArray, start: Int, end: Int): Boolean =
|
|
911
|
+
start + 6 <= end &&
|
|
912
|
+
bytes[start] == 'E'.code.toByte() &&
|
|
913
|
+
bytes[start + 1] == 'x'.code.toByte() &&
|
|
914
|
+
bytes[start + 2] == 'i'.code.toByte() &&
|
|
915
|
+
bytes[start + 3] == 'f'.code.toByte() &&
|
|
916
|
+
bytes[start + 4] == 0.toByte() &&
|
|
917
|
+
bytes[start + 5] == 0.toByte()
|
|
918
|
+
|
|
919
|
+
private fun parseTiffOrientation(bytes: ByteArray, start: Int, end: Int): Int {
|
|
920
|
+
if (start < 0 || start > end - 8 || end > bytes.size) return 1
|
|
921
|
+
val littleEndian = when {
|
|
922
|
+
bytes[start] == 'I'.code.toByte() && bytes[start + 1] == 'I'.code.toByte() -> true
|
|
923
|
+
bytes[start] == 'M'.code.toByte() && bytes[start + 1] == 'M'.code.toByte() -> false
|
|
924
|
+
else -> return 1
|
|
925
|
+
}
|
|
926
|
+
if (readU16(bytes, start + 2, littleEndian) != 0x002a) return 1
|
|
927
|
+
val ifdOffset = readInt32(bytes, start + 4, littleEndian)
|
|
928
|
+
if (ifdOffset < 8 || ifdOffset > end - start - 2) return 1
|
|
929
|
+
val ifdStart = start + ifdOffset
|
|
930
|
+
val entryCount = readU16(bytes, ifdStart, littleEndian)
|
|
931
|
+
for (i in 0 until entryCount) {
|
|
932
|
+
val entryOffset = ifdStart + 2 + i * 12
|
|
933
|
+
if (entryOffset > end - 12) break
|
|
934
|
+
val tag = readU16(bytes, entryOffset, littleEndian)
|
|
935
|
+
if (tag == 0x0112) {
|
|
936
|
+
val fieldType = readU16(bytes, entryOffset + 2, littleEndian)
|
|
937
|
+
val count = readInt32(bytes, entryOffset + 4, littleEndian)
|
|
938
|
+
if (count != 1) return 1
|
|
939
|
+
val value = when (fieldType) {
|
|
940
|
+
3 -> {
|
|
941
|
+
val primary = readU16(bytes, entryOffset + 8, littleEndian)
|
|
942
|
+
if (primary in 1..8) primary else readU16(bytes, entryOffset + 10, littleEndian)
|
|
943
|
+
}
|
|
944
|
+
4 -> readInt32(bytes, entryOffset + 8, littleEndian)
|
|
945
|
+
1 -> bytes[entryOffset + 8].toInt() and 0xff
|
|
946
|
+
else -> 1
|
|
947
|
+
}
|
|
948
|
+
return if (value in 1..8) value else 1
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
return 1
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
private fun readU16(bytes: ByteArray, offset: Int, littleEndian: Boolean): Int =
|
|
955
|
+
if (littleEndian) {
|
|
956
|
+
(bytes[offset].toInt() and 0xff) or ((bytes[offset + 1].toInt() and 0xff) shl 8)
|
|
957
|
+
} else {
|
|
958
|
+
readU16Be(bytes, offset)
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
private fun readU16Be(bytes: ByteArray, offset: Int): Int =
|
|
962
|
+
((bytes[offset].toInt() and 0xff) shl 8) or (bytes[offset + 1].toInt() and 0xff)
|
|
963
|
+
|
|
964
|
+
private fun readInt32(bytes: ByteArray, offset: Int, littleEndian: Boolean): Int =
|
|
965
|
+
if (littleEndian) readInt32Le(bytes, offset) else readInt32Be(bytes, offset)
|
|
966
|
+
|
|
967
|
+
private fun readInt32Le(bytes: ByteArray, offset: Int): Int =
|
|
968
|
+
(bytes[offset].toInt() and 0xff) or
|
|
969
|
+
((bytes[offset + 1].toInt() and 0xff) shl 8) or
|
|
970
|
+
((bytes[offset + 2].toInt() and 0xff) shl 16) or
|
|
971
|
+
((bytes[offset + 3].toInt() and 0xff) shl 24)
|
|
972
|
+
|
|
973
|
+
private fun readInt32Be(bytes: ByteArray, offset: Int): Int =
|
|
974
|
+
((bytes[offset].toInt() and 0xff) shl 24) or
|
|
975
|
+
((bytes[offset + 1].toInt() and 0xff) shl 16) or
|
|
976
|
+
((bytes[offset + 2].toInt() and 0xff) shl 8) or
|
|
977
|
+
(bytes[offset + 3].toInt() and 0xff)
|
|
978
|
+
|
|
979
|
+
private fun isSafeToken(token: String): Boolean =
|
|
980
|
+
token.isNotEmpty() &&
|
|
981
|
+
!token.contains('/') &&
|
|
982
|
+
!token.contains('\\') &&
|
|
983
|
+
!token.contains("..")
|
|
984
|
+
|
|
985
|
+
private fun isValidEntry(entry: StartupEntry): Boolean =
|
|
986
|
+
entry.keyHash.isNotEmpty() &&
|
|
987
|
+
isSafeToken(entry.diskFile) &&
|
|
988
|
+
(entry.rawDiskFile == null || isSafeToken(entry.rawDiskFile)) &&
|
|
989
|
+
entry.width > 0 &&
|
|
990
|
+
entry.height > 0 &&
|
|
991
|
+
entry.width.toLong() * entry.height.toLong() <= 4_194_304L
|
|
992
|
+
|
|
993
|
+
internal fun sha256Hex(bytes: ByteArray): String =
|
|
994
|
+
MessageDigest.getInstance("SHA-256")
|
|
995
|
+
.digest(bytes)
|
|
996
|
+
.joinToString("") { "%02x".format(Locale.ROOT, it.toInt() and 0xff) }
|
|
997
|
+
|
|
998
|
+
internal fun encodeEntriesJson(entries: List<StartupEntry>): String {
|
|
999
|
+
val array = JSONArray()
|
|
1000
|
+
for (entry in entries) {
|
|
1001
|
+
val obj = JSONObject()
|
|
1002
|
+
.put("keyHash", entry.keyHash)
|
|
1003
|
+
.put("diskFile", entry.diskFile)
|
|
1004
|
+
.put("width", entry.width)
|
|
1005
|
+
.put("height", entry.height)
|
|
1006
|
+
.put("round", entry.round)
|
|
1007
|
+
.put("launch", entry.launch)
|
|
1008
|
+
if (!entry.rawDiskFile.isNullOrEmpty()) {
|
|
1009
|
+
obj.put("rawDiskFile", entry.rawDiskFile)
|
|
1010
|
+
}
|
|
1011
|
+
array.put(obj)
|
|
1012
|
+
}
|
|
1013
|
+
return array.toString()
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
internal fun decodeEntriesJson(text: String): List<StartupEntry> {
|
|
1017
|
+
val trimmed = text.trim()
|
|
1018
|
+
if (trimmed.isEmpty()) return emptyList()
|
|
1019
|
+
val array = JSONArray(trimmed)
|
|
1020
|
+
val result = ArrayList<StartupEntry>(array.length())
|
|
1021
|
+
for (i in 0 until array.length()) {
|
|
1022
|
+
val obj = array.optJSONObject(i) ?: continue
|
|
1023
|
+
val keyHash = obj.optString("keyHash", "").takeIf { it.isNotEmpty() } ?: continue
|
|
1024
|
+
val diskFile = obj.optString("diskFile", "").takeIf { it.isNotEmpty() } ?: continue
|
|
1025
|
+
val rawDiskFile = obj.optString("rawDiskFile", "").takeIf { it.isNotEmpty() }
|
|
1026
|
+
val width = obj.optInt("width", 0)
|
|
1027
|
+
val height = obj.optInt("height", 0)
|
|
1028
|
+
if (width <= 0 || height <= 0) continue
|
|
1029
|
+
val round = obj.optBoolean("round", false)
|
|
1030
|
+
val launch = obj.optInt("launch", 0)
|
|
1031
|
+
result.add(
|
|
1032
|
+
StartupEntry(
|
|
1033
|
+
keyHash = keyHash,
|
|
1034
|
+
diskFile = diskFile,
|
|
1035
|
+
rawDiskFile = rawDiskFile,
|
|
1036
|
+
width = width,
|
|
1037
|
+
height = height,
|
|
1038
|
+
round = round,
|
|
1039
|
+
launch = launch,
|
|
1040
|
+
),
|
|
1041
|
+
)
|
|
1042
|
+
}
|
|
1043
|
+
return result
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
internal fun readEntries(file: File): List<StartupEntry> {
|
|
1047
|
+
if (!file.isFile) return emptyList()
|
|
1048
|
+
return try {
|
|
1049
|
+
decodeEntriesJson(file.readText(Charsets.UTF_8))
|
|
1050
|
+
} catch (_: Exception) {
|
|
1051
|
+
emptyList()
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
internal fun drainSchedulerForTesting() {
|
|
1056
|
+
try {
|
|
1057
|
+
scheduler.submit {}.get(5, TimeUnit.SECONDS)
|
|
1058
|
+
} catch (_: Exception) {
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
internal fun resetForTesting(file: File? = null, cacheDir: File? = null) {
|
|
1063
|
+
synchronized(stateLock) {
|
|
1064
|
+
debounceFuture?.cancel(false)
|
|
1065
|
+
debounceFuture = null
|
|
1066
|
+
recorded.clear()
|
|
1067
|
+
recordedKeys.clear()
|
|
1068
|
+
activeStartupDiskFiles.clear()
|
|
1069
|
+
pendingFallbackSources.clear()
|
|
1070
|
+
recordStartTimeMs = null
|
|
1071
|
+
recordingClosed = false
|
|
1072
|
+
flushScheduled = false
|
|
1073
|
+
startupFileOverride = file
|
|
1074
|
+
baseCacheDir = cacheDir ?: file?.parentFile
|
|
1075
|
+
lastPrewarmMetrics = PrewarmMetrics()
|
|
1076
|
+
}
|
|
1077
|
+
clearMemoryCache()
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
internal fun flushForTesting(forceClose: Boolean = true) {
|
|
1081
|
+
val entries: List<StartupEntry>
|
|
1082
|
+
val fallbackMap: Map<String, String>
|
|
1083
|
+
val file: File?
|
|
1084
|
+
val cacheDir: File?
|
|
1085
|
+
synchronized(stateLock) {
|
|
1086
|
+
debounceFuture?.cancel(false)
|
|
1087
|
+
debounceFuture = null
|
|
1088
|
+
if (!forceClose && recorded.size < MIN_SETTLED_COUNT) {
|
|
1089
|
+
return
|
|
1090
|
+
}
|
|
1091
|
+
recordingClosed = true
|
|
1092
|
+
flushScheduled = false
|
|
1093
|
+
entries = ArrayList(recorded)
|
|
1094
|
+
fallbackMap = HashMap(pendingFallbackSources)
|
|
1095
|
+
pendingFallbackSources.clear()
|
|
1096
|
+
file = startupFile()
|
|
1097
|
+
cacheDir = currentCacheDir()
|
|
1098
|
+
}
|
|
1099
|
+
if (cacheDir != null && fallbackMap.isNotEmpty()) {
|
|
1100
|
+
materializeFallbackSources(cacheDir, fallbackMap)
|
|
1101
|
+
}
|
|
1102
|
+
if (file != null) {
|
|
1103
|
+
persist(entries, file)
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
}
|