@onekeyfe/react-native-image 6.7.0-alpha.464 → 6.7.0-alpha.475

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.
@@ -21,7 +21,7 @@ import java.util.concurrent.CancellationException
21
21
 
22
22
  // Only source PNGs are persisted; transformed resources can have other dimensions.
23
23
  internal fun oneKeyImageMemoryDiskStrategy(uri: String): DiskCacheStrategy =
24
- if (OneKeyBlockieAvatar.isAvatarUri(uri)) DiskCacheStrategy.DATA else DiskCacheStrategy.AUTOMATIC
24
+ if (OneKeyBlockieAvatar.isAvatarUri(uri) || uri.startsWith("data:")) DiskCacheStrategy.DATA else DiskCacheStrategy.AUTOMATIC
25
25
 
26
26
  internal val oneKeyAvatarCacheFileOption: Option<Boolean> =
27
27
  Option.memory("onekey-image.blockie-source-cache-v1", false)
@@ -95,6 +95,7 @@ class HybridOneKeyImageCache : HybridOneKeyImageCacheSpec() {
95
95
  val context = NitroModules.applicationContext
96
96
  ?: throw IllegalStateException("React application context is unavailable")
97
97
  withContext(Dispatchers.Main) {
98
+ OneKeyMediaPreviewCache.get(context).clearMemory()
98
99
  Glide.get(context).clearMemory()
99
100
  OneKeyImageMemoryVariantRegistry.clear()
100
101
  }
@@ -103,6 +104,11 @@ class HybridOneKeyImageCache : HybridOneKeyImageCacheSpec() {
103
104
  override fun clearDisk(): Promise<Unit> = Promise.async {
104
105
  val context = NitroModules.applicationContext
105
106
  ?: throw IllegalStateException("React application context is unavailable")
107
+ kotlinx.coroutines.suspendCancellableCoroutine<Unit> { continuation ->
108
+ android.os.Handler(android.os.Looper.getMainLooper()).post {
109
+ OneKeyMediaPreviewCache.get(context).clearDisk { continuation.resumeWith(Result.success(Unit)) }
110
+ }
111
+ }
106
112
  Glide.get(context).clearDiskCache()
107
113
  }
108
114
 
@@ -110,9 +116,15 @@ class HybridOneKeyImageCache : HybridOneKeyImageCacheSpec() {
110
116
  val context = NitroModules.applicationContext
111
117
  ?: throw IllegalStateException("React application context is unavailable")
112
118
  withContext(Dispatchers.Main) {
119
+ OneKeyMediaPreviewCache.get(context).clearMemory()
113
120
  Glide.get(context).clearMemory()
114
121
  OneKeyImageMemoryVariantRegistry.clear()
115
122
  }
123
+ kotlinx.coroutines.suspendCancellableCoroutine<Unit> { continuation ->
124
+ android.os.Handler(android.os.Looper.getMainLooper()).post {
125
+ OneKeyMediaPreviewCache.get(context).clearDisk { continuation.resumeWith(Result.success(Unit)) }
126
+ }
127
+ }
116
128
  Glide.get(context).clearDiskCache()
117
129
  }
118
130
 
@@ -80,6 +80,11 @@ internal object OneKeyImageGlideRegistry {
80
80
  InputStream::class.java,
81
81
  OneKeyImageRemoteModelLoaderFactory(imageHttpClient),
82
82
  )
83
+ registry.append(
84
+ ByteBuffer::class.java,
85
+ SVG::class.java,
86
+ OneKeyByteBufferSvgDecoder(),
87
+ )
83
88
  registry.append(
84
89
  InputStream::class.java,
85
90
  SVG::class.java,
@@ -255,6 +260,19 @@ private class OneKeyDataUriFetcher(private val dataUri: String) : DataFetcher<By
255
260
  }
256
261
  }
257
262
 
263
+ private class OneKeyByteBufferSvgDecoder : ResourceDecoder<ByteBuffer, SVG> {
264
+ private val delegate = OneKeySvgDecoder()
265
+
266
+ override fun handles(source: ByteBuffer, options: Options): Boolean = true
267
+
268
+ override fun decode(source: ByteBuffer, width: Int, height: Int, options: Options): Resource<SVG> {
269
+ val copy = source.asReadOnlyBuffer()
270
+ copy.position(0)
271
+ OneKeyImageSafety.requireEncodedLength(copy.remaining().toLong(), OneKeyImageSafety.MAX_ENCODED_BYTES)
272
+ return delegate.decode(com.bumptech.glide.util.ByteBufferUtil.toStream(copy), width, height, options)
273
+ }
274
+ }
275
+
258
276
  private class OneKeySvgDecoder : ResourceDecoder<InputStream, SVG> {
259
277
  override fun handles(source: InputStream, options: Options): Boolean = true
260
278
 
@@ -0,0 +1,199 @@
1
+ package com.margelo.nitro.onekeyimage
2
+
3
+ import android.content.Context
4
+ import android.graphics.Bitmap
5
+ import android.graphics.BitmapFactory
6
+ import android.os.Handler
7
+ import android.os.Looper
8
+ import android.util.LruCache
9
+ import com.bumptech.glide.load.engine.cache.DiskLruCacheWrapper
10
+ import com.bumptech.glide.signature.ObjectKey
11
+ import java.io.ByteArrayOutputStream
12
+ import java.io.File
13
+ import java.security.MessageDigest
14
+ import java.util.UUID
15
+ import java.util.concurrent.Future
16
+ import java.util.concurrent.LinkedBlockingQueue
17
+ import java.util.concurrent.ThreadPoolExecutor
18
+ import java.util.concurrent.TimeUnit
19
+
20
+ /** Native-only process cache. View slots retain their players and surfaces. */
21
+ class OneKeyMediaPreviewCache private constructor(context: Context, directory: File) {
22
+ companion object {
23
+ @Volatile private var instance: OneKeyMediaPreviewCache? = null
24
+ fun get(context: Context): OneKeyMediaPreviewCache = instance ?: synchronized(this) {
25
+ instance ?: OneKeyMediaPreviewCache(context.applicationContext,
26
+ File(context.cacheDir, "onekey-media-preview-v1")).also { instance = it }
27
+ }
28
+ fun targetEdge(pixels: Int): Int = listOf(128, 256, 512, 1024).firstOrNull { it >= pixels } ?: 1024
29
+ internal fun storageKey(uri: String, headers: Map<String, String>, edge: Int, fit: String): String {
30
+ val fields = headers.entries.map { it.key.lowercase(java.util.Locale.ROOT) to it.value }
31
+ .sortedWith(compareBy({ it.first }, { it.second }))
32
+ val values = listOf("onekey-media-preview-v1", uri, edge.toString(), fit) + fields.flatMap { listOf(it.first, it.second) }
33
+ val canonical = values.joinToString("") { "${it.toByteArray(Charsets.UTF_8).size}:$it" }
34
+ return MessageDigest.getInstance("SHA-256").digest(canonical.toByteArray(Charsets.UTF_8))
35
+ .joinToString("") { "%02x".format(it.toInt() and 255) }
36
+ }
37
+ internal fun isolated(context: Context, directory: File) = OneKeyMediaPreviewCache(context, directory)
38
+ }
39
+ class Subscription internal constructor(internal val key: String,
40
+ internal val image: (Bitmap) -> Unit, internal val extract: (UUID) -> Unit,
41
+ internal val revoked: () -> Unit, internal val failure: () -> Unit) {
42
+ internal var cancelled = false
43
+ }
44
+ private class Flight(val key: String, val storageKey: String, val policy: String,
45
+ val memoryGeneration: Int, val diskGeneration: Int) {
46
+ val subscribers = mutableListOf<Subscription>()
47
+ var lease: UUID? = null
48
+ var timeout: Runnable? = null
49
+ var ready = false
50
+ var lookupTask: Future<*>? = null
51
+ }
52
+ private val main = Handler(Looper.getMainLooper())
53
+ private val io = ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, LinkedBlockingQueue()) { task ->
54
+ Thread(task, "onekey-media-preview-io").apply { isDaemon = true }
55
+ }
56
+ private val disk = DiskLruCacheWrapper.create(directory, 64L * 1024 * 1024)
57
+ private val memory = object : LruCache<String, Bitmap>(16 * 1024 * 1024) {
58
+ override fun sizeOf(key: String, value: Bitmap): Int = value.allocationByteCount
59
+ }
60
+ private val flights = linkedMapOf<String, Flight>()
61
+ private val queue = ArrayDeque<String>()
62
+ private var active = 0
63
+ private var pendingPersistenceBytes = 0
64
+ private var memoryGeneration = 0
65
+ private var diskGeneration = 0
66
+ private fun checkMain() = check(Looper.myLooper() == Looper.getMainLooper())
67
+ private fun memoryPolicy(policy: String) = policy == "memory" || policy == "memory-disk"
68
+ private fun diskPolicy(policy: String) = policy == "disk" || policy == "memory-disk"
69
+
70
+ fun request(uri: String, headers: Map<String, String>, edge: Int, fit: String, policy: String,
71
+ onImage: (Bitmap) -> Unit, onExtract: (UUID) -> Unit, onRevoked: () -> Unit,
72
+ onFailure: () -> Unit): Subscription {
73
+ checkMain()
74
+ val storageKey = storageKey(uri, headers, targetEdge(edge.coerceAtLeast(1)), fit)
75
+ val key = "$storageKey|$policy"
76
+ val subscriber = Subscription(key, onImage, onExtract, onRevoked, onFailure)
77
+ flights[key]?.let { it.subscribers.add(subscriber); return subscriber }
78
+ if (flights.size >= 130) { main.post { if (!subscriber.cancelled) subscriber.failure() }; return subscriber }
79
+ val flight = Flight(key, storageKey, policy, memoryGeneration, diskGeneration)
80
+ flight.subscribers.add(subscriber); flights[key] = flight
81
+ if (memoryPolicy(policy)) memory.get(storageKey)?.let { bitmap ->
82
+ main.post { finish(flight, bitmap) }; return subscriber
83
+ }
84
+ flight.lookupTask = io.submit {
85
+ val bitmap = if (diskPolicy(policy)) runCatching {
86
+ disk.get(ObjectKey(storageKey))?.let { file ->
87
+ if (file.length() > 8L * 1024 * 1024) null else {
88
+ val data = file.inputStream().use { input ->
89
+ val output = ByteArrayOutputStream()
90
+ val buffer = ByteArray(8192)
91
+ while (output.size() <= 8 * 1024 * 1024) {
92
+ val count = input.read(buffer, 0, minOf(buffer.size, 8 * 1024 * 1024 + 1 - output.size()))
93
+ if (count < 0) break
94
+ output.write(buffer, 0, count)
95
+ }
96
+ output.toByteArray()
97
+ }
98
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
99
+ if (data.size > 8 * 1024 * 1024) null else {
100
+ BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
101
+ if (bounds.outWidth in 1..1024 && bounds.outHeight in 1..1024)
102
+ BitmapFactory.decodeByteArray(data, 0, data.size) else null
103
+ }
104
+ }
105
+ }.also { if (it == null) disk.delete(ObjectKey(storageKey)) }
106
+ }.getOrNull() else null
107
+ main.post {
108
+ if (flights[key] !== flight) return@post
109
+ if (bitmap != null && flight.diskGeneration == diskGeneration) {
110
+ if (memoryPolicy(policy) && flight.memoryGeneration == memoryGeneration) storeMemory(storageKey, bitmap)
111
+ finish(flight, bitmap)
112
+ } else { flight.ready = true; queue.addLast(key); pump() }
113
+ }
114
+ }
115
+ return subscriber
116
+ }
117
+ fun cancel(subscription: Subscription?) {
118
+ checkMain()
119
+ if (subscription == null) return
120
+ subscription.cancelled = true
121
+ val flight = flights[subscription.key] ?: return
122
+ val index = flight.subscribers.indexOf(subscription)
123
+ if (index < 0) return
124
+ val owned = index == 0 && flight.lease != null
125
+ flight.subscribers.removeAt(index)
126
+ if (owned) {
127
+ flight.timeout?.let(main::removeCallbacks); flight.lease = null; active--
128
+ subscription.revoked()
129
+ }
130
+ if (flight.subscribers.isEmpty()) {
131
+ cancelLookup(flight)
132
+ flights.remove(flight.key); queue.removeAll { it == flight.key }
133
+ } else if (owned) queue.addFirst(flight.key)
134
+ pump()
135
+ }
136
+ fun fail(lease: UUID) {
137
+ checkMain(); flights.values.firstOrNull { it.lease == lease }?.let { finish(it, null) }
138
+ }
139
+ fun complete(lease: UUID, bitmap: Bitmap) {
140
+ checkMain()
141
+ val flight = flights.values.firstOrNull { it.lease == lease } ?: return
142
+ if (bitmap.width !in 1..1024 || bitmap.height !in 1..1024) { finish(flight, null); return }
143
+ if (memoryPolicy(flight.policy) && flight.memoryGeneration == memoryGeneration) storeMemory(flight.storageKey, bitmap)
144
+ finish(flight, bitmap)
145
+ val cost = bitmap.allocationByteCount
146
+ if (!diskPolicy(flight.policy) || pendingPersistenceBytes + cost > 16 * 1024 * 1024) return
147
+ pendingPersistenceBytes += cost
148
+ io.execute {
149
+ val data = runCatching { ByteArrayOutputStream().use {
150
+ bitmap.compress(Bitmap.CompressFormat.PNG, 100, it); it.toByteArray()
151
+ } }.getOrNull()
152
+ main.post {
153
+ if (flight.diskGeneration != diskGeneration || data == null || data.size > 8 * 1024 * 1024) {
154
+ pendingPersistenceBytes -= cost; return@post
155
+ }
156
+ // Serial writes and clears seal the generation-check/write window.
157
+ io.execute {
158
+ runCatching { disk.put(ObjectKey(flight.storageKey)) { file ->
159
+ file.outputStream().use { it.write(data) }; true
160
+ } }
161
+ main.post { pendingPersistenceBytes -= cost }
162
+ }
163
+ }
164
+ }
165
+ }
166
+ fun clearMemory() { checkMain(); memoryGeneration++; memory.evictAll() }
167
+ fun clearDisk(completion: () -> Unit) {
168
+ checkMain(); diskGeneration++
169
+ io.execute { runCatching { disk.clear() }; completion() }
170
+ }
171
+ private fun storeMemory(key: String, bitmap: Bitmap) {
172
+ if (bitmap.allocationByteCount <= 16 * 1024 * 1024) memory.put(key, bitmap)
173
+ while (memory.snapshot().size > 64) memory.remove(memory.snapshot().keys.first())
174
+ }
175
+ private fun pump() {
176
+ while (active < 2 && queue.isNotEmpty()) {
177
+ val flight = flights[queue.removeFirst()] ?: continue
178
+ if (!flight.ready || flight.lease != null || flight.subscribers.isEmpty()) continue
179
+ val lease = UUID.randomUUID(); flight.lease = lease; active++
180
+ val timeout = Runnable { if (flight.lease == lease) finish(flight, null) }
181
+ flight.timeout = timeout; main.postDelayed(timeout, 10_000)
182
+ flight.subscribers.first().extract(lease)
183
+ }
184
+ }
185
+ private fun cancelLookup(flight: Flight) {
186
+ flight.lookupTask?.let { task -> task.cancel(false); (task as? Runnable)?.let(io::remove) }
187
+ flight.lookupTask = null
188
+ }
189
+ private fun finish(flight: Flight, bitmap: Bitmap?) {
190
+ if (flights[flight.key] !== flight) return
191
+ cancelLookup(flight)
192
+ flights.remove(flight.key); queue.removeAll { it == flight.key }
193
+ if (flight.lease != null) { active--; flight.subscribers.firstOrNull()?.revoked?.invoke() }
194
+ flight.timeout?.let(main::removeCallbacks); flight.lease = null
195
+ val subscribers = flight.subscribers.toList(); flight.subscribers.clear()
196
+ subscribers.filterNot { it.cancelled }.forEach { if (bitmap != null) it.image(bitmap) else it.failure() }
197
+ pump()
198
+ }
199
+ }
@@ -46,7 +46,8 @@ class OneKeyBlockieAvatarLoaderTest {
46
46
  assertFalse(strategy.isDataCacheable(DataSource.DATA_DISK_CACHE))
47
47
  assertFalse(DiskCacheStrategy.ALL.isDataCacheable(DataSource.LOCAL))
48
48
  assertEquals(DiskCacheStrategy.AUTOMATIC, oneKeyImageMemoryDiskStrategy("https://example.com/image.png"))
49
- assertEquals(DiskCacheStrategy.AUTOMATIC, oneKeyImageMemoryDiskStrategy("data:image/png;base64,AA=="))
49
+ assertEquals(DiskCacheStrategy.DATA, oneKeyImageMemoryDiskStrategy("data:image/png;base64,AA=="))
50
+ assertEquals(DiskCacheStrategy.DATA, oneKeyImageMemoryDiskStrategy("data:image/svg+xml;base64,PHN2Zy8+"))
50
51
  assertFalse(DiskCacheStrategy.AUTOMATIC.isDataCacheable(DataSource.LOCAL))
51
52
  }
52
53
 
@@ -73,6 +73,7 @@ final class HybridOneKeyImageCache: HybridOneKeyImageCacheSpec {
73
73
 
74
74
  func clearMemory() throws -> Promise<Void> {
75
75
  Promise.async {
76
+ await MainActor.run { OneKeyMediaPreviewCache.shared.clearMemory() }
76
77
  SDImageCache.shared.clearMemory()
77
78
  // OneKey patch: Clear the dedicated local-avatar cache with public cache operations.
78
79
  OneKeyAvatarImageLoader.cache.clearMemory()
@@ -82,6 +83,11 @@ final class HybridOneKeyImageCache: HybridOneKeyImageCacheSpec {
82
83
 
83
84
  func clearDisk() throws -> Promise<Void> {
84
85
  Promise.async {
86
+ await withCheckedContinuation { continuation in
87
+ DispatchQueue.main.async {
88
+ OneKeyMediaPreviewCache.shared.clearDisk { continuation.resume() }
89
+ }
90
+ }
85
91
  await withCheckedContinuation { continuation in
86
92
  SDImageCache.shared.clearDisk { continuation.resume() }
87
93
  }
@@ -92,11 +98,23 @@ final class HybridOneKeyImageCache: HybridOneKeyImageCacheSpec {
92
98
  }
93
99
 
94
100
  func clearAll() throws -> Promise<Void> {
95
- SDImageCache.shared.clearMemory()
96
- // OneKey patch: The avatar cache is shared by render and preload requests.
97
- OneKeyAvatarImageLoader.cache.clearMemory()
98
- OneKeyImageMemoryVariantRegistry.shared.clear()
99
- return try clearDisk()
101
+ Promise.async {
102
+ await MainActor.run { OneKeyMediaPreviewCache.shared.clearMemory() }
103
+ SDImageCache.shared.clearMemory()
104
+ OneKeyAvatarImageLoader.cache.clearMemory()
105
+ OneKeyImageMemoryVariantRegistry.shared.clear()
106
+ await withCheckedContinuation { continuation in
107
+ DispatchQueue.main.async {
108
+ OneKeyMediaPreviewCache.shared.clearDisk { continuation.resume() }
109
+ }
110
+ }
111
+ await withCheckedContinuation { continuation in
112
+ SDImageCache.shared.clearDisk { continuation.resume() }
113
+ }
114
+ await withCheckedContinuation { continuation in
115
+ OneKeyAvatarImageLoader.cache.clearDisk { continuation.resume() }
116
+ }
117
+ }
100
118
  }
101
119
 
102
120
  private static func preload(
@@ -0,0 +1,201 @@
1
+ import CryptoKit
2
+ import Foundation
3
+ import ImageIO
4
+ import SDWebImage
5
+ import UIKit
6
+
7
+ /// Native-only process cache. Players remain owned by their view slots.
8
+ public final class OneKeyMediaPreviewCache {
9
+ public static let shared = OneKeyMediaPreviewCache()
10
+ public static func targetEdge(_ pixels: CGFloat) -> Int {
11
+ [128, 256, 512, 1024].first { CGFloat($0) >= pixels } ?? 1024
12
+ }
13
+ public final class Subscription {
14
+ fileprivate var cancelled = false
15
+ fileprivate let key: String
16
+ fileprivate let image: (UIImage) -> Void
17
+ fileprivate let extract: (UUID) -> Void
18
+ fileprivate let revoked: () -> Void
19
+ fileprivate let failure: () -> Void
20
+ fileprivate init(key: String, image: @escaping (UIImage) -> Void, extract: @escaping (UUID) -> Void,
21
+ revoked: @escaping () -> Void, failure: @escaping () -> Void) {
22
+ self.key = key; self.image = image; self.extract = extract; self.revoked = revoked; self.failure = failure
23
+ }
24
+ }
25
+ private final class Flight {
26
+ let key: String
27
+ let storageKey: String
28
+ let policy: String
29
+ let memoryGeneration: Int
30
+ let diskGeneration: Int
31
+ var subscribers: [Subscription] = []
32
+ var lease: UUID?
33
+ var lookupWorkItem: DispatchWorkItem?
34
+ var timeout: DispatchWorkItem?
35
+ var ready = false
36
+ init(key: String, storageKey: String, policy: String, memory: Int, disk: Int) {
37
+ self.key = key; self.storageKey = storageKey; self.policy = policy
38
+ memoryGeneration = memory; diskGeneration = disk
39
+ }
40
+ }
41
+ private let cache: SDImageCache
42
+ private let io = DispatchQueue(label: "onekey.media-preview.io", qos: .userInitiated)
43
+ private var flights: [String: Flight] = [:]
44
+ private var queue: [String] = []
45
+ private var active = 0
46
+ private var pendingPersistenceBytes = 0
47
+ private var memoryGeneration = 0
48
+ private var diskGeneration = 0
49
+ init(namespace: String = "onekey-media-preview-v1") {
50
+ let config = SDImageCacheConfig()
51
+ config.maxMemoryCost = 16 * 1024 * 1024; config.maxMemoryCount = 64
52
+ config.maxDiskSize = 64 * 1024 * 1024; config.maxDiskAge = 30 * 24 * 60 * 60
53
+ cache = SDImageCache(namespace: namespace, diskCacheDirectory: nil, config: config)
54
+ }
55
+ static func storageKey(uri: String, headers: [String: String], edge: Int, fit: String) -> String {
56
+ let normalized: [(String, String)] = headers.map { ($0.key.lowercased(), $0.value) }
57
+ let fields: [(String, String)] = normalized.sorted {
58
+ $0.0 == $1.0 ? $0.1 < $1.1 : $0.0 < $1.0
59
+ }
60
+ let values = ["onekey-media-preview-v1", uri, String(edge), fit] + fields.flatMap { [$0.0, $0.1] }
61
+ let canonical = values.map { "\($0.utf8.count):\($0)" }.joined()
62
+ return SHA256.hash(data: Data(canonical.utf8)).map { String(format: "%02x", $0) }.joined()
63
+ }
64
+ @discardableResult
65
+ public func request(uri: String, headers: [String: String], edge: Int, fit: String, policy: String,
66
+ onImage: @escaping (UIImage) -> Void, onExtract: @escaping (UUID) -> Void,
67
+ onRevoked: @escaping () -> Void, onFailure: @escaping () -> Void) -> Subscription {
68
+ dispatchPrecondition(condition: .onQueue(.main))
69
+ let storageKey = Self.storageKey(uri: uri, headers: headers,
70
+ edge: Self.targetEdge(CGFloat(max(1, edge))), fit: fit)
71
+ let key = "\(storageKey)|\(policy)"
72
+ let subscriber = Subscription(key: key, image: onImage, extract: onExtract, revoked: onRevoked, failure: onFailure)
73
+ if let flight = flights[key] { flight.subscribers.append(subscriber); return subscriber }
74
+ guard flights.count < 130 else {
75
+ DispatchQueue.main.async { if !subscriber.cancelled { subscriber.failure() } }
76
+ return subscriber
77
+ }
78
+ let flight = Flight(key: key, storageKey: storageKey, policy: policy, memory: memoryGeneration, disk: diskGeneration)
79
+ flight.subscribers = [subscriber]; flights[key] = flight
80
+ if permitsMemory(policy), let image = cache.imageFromMemoryCache(forKey: storageKey) {
81
+ DispatchQueue.main.async { [weak self] in self?.finish(flight, image: image) }; return subscriber
82
+ }
83
+ let lookup = DispatchWorkItem { [weak self, weak flight] in
84
+ guard let self, let flight, flight.lookupWorkItem?.isCancelled == false else { return }
85
+ var image: UIImage?
86
+ if self.permitsDisk(policy), let path = self.cache.cachePath(forKey: storageKey),
87
+ let file = FileHandle(forReadingAtPath: path) {
88
+ defer { try? file.close() }
89
+ if let data = try? file.read(upToCount: 8 * 1024 * 1024 + 1), data.count <= 8 * 1024 * 1024,
90
+ let source = CGImageSourceCreateWithData(data as CFData, nil),
91
+ let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
92
+ let width = properties[kCGImagePropertyPixelWidth] as? Int,
93
+ let height = properties[kCGImagePropertyPixelHeight] as? Int,
94
+ (1...1024).contains(width), (1...1024).contains(height) {
95
+ let options = [kCGImageSourceShouldCacheImmediately: true] as CFDictionary
96
+ image = CGImageSourceCreateImageAtIndex(source, 0, options).map { UIImage(cgImage: $0) }
97
+ }
98
+ if image == nil { self.cache.removeImageFromDisk(forKey: storageKey) }
99
+ }
100
+ DispatchQueue.main.async {
101
+ guard self.flights[key] === flight else { return }
102
+ if let image, flight.diskGeneration == self.diskGeneration {
103
+ if self.permitsMemory(policy), flight.memoryGeneration == self.memoryGeneration {
104
+ self.cache.storeImage(toMemory: image, forKey: storageKey)
105
+ }
106
+ self.finish(flight, image: image)
107
+ } else { flight.ready = true; self.queue.append(key); self.pump() }
108
+ }
109
+ }
110
+ flight.lookupWorkItem = lookup
111
+ io.async(execute: lookup)
112
+ return subscriber
113
+ }
114
+ public func cancel(_ subscription: Subscription?) {
115
+ dispatchPrecondition(condition: .onQueue(.main))
116
+ guard let subscription else { return }
117
+ subscription.cancelled = true
118
+ guard let flight = flights[subscription.key],
119
+ let index = flight.subscribers.firstIndex(where: { $0 === subscription }) else { return }
120
+ let owned = index == 0 && flight.lease != nil
121
+ flight.subscribers.remove(at: index)
122
+ if owned {
123
+ flight.timeout?.cancel(); flight.timeout = nil; flight.lease = nil; active -= 1; subscription.revoked()
124
+ }
125
+ if flight.subscribers.isEmpty {
126
+ flight.lookupWorkItem?.cancel()
127
+ flights.removeValue(forKey: flight.key); queue.removeAll { $0 == flight.key }
128
+ } else if owned { queue.insert(flight.key, at: 0) }
129
+ pump()
130
+ }
131
+ public func fail(_ lease: UUID) {
132
+ dispatchPrecondition(condition: .onQueue(.main))
133
+ guard let flight = flights.values.first(where: { $0.lease == lease }) else { return }; finish(flight, image: nil)
134
+ }
135
+ /// Producers submit bounded, orientation-normalized pixels, never an active player.
136
+ public func complete(_ lease: UUID, image: UIImage) {
137
+ dispatchPrecondition(condition: .onQueue(.main))
138
+ guard let flight = flights.values.first(where: { $0.lease == lease }) else { return }
139
+ guard image.size.width > 0, image.size.height > 0,
140
+ image.size.width * image.scale <= 1024, image.size.height * image.scale <= 1024 else {
141
+ finish(flight, image: nil); return
142
+ }
143
+ if permitsMemory(flight.policy), flight.memoryGeneration == memoryGeneration {
144
+ cache.storeImage(toMemory: image, forKey: flight.storageKey)
145
+ }
146
+ finish(flight, image: image)
147
+ let cost = Int(image.size.width * image.scale) * Int(image.size.height * image.scale) * 4
148
+ guard permitsDisk(flight.policy), pendingPersistenceBytes + cost <= 16 * 1024 * 1024 else { return }
149
+ pendingPersistenceBytes += cost
150
+ io.async { [weak self] in
151
+ guard let self else { return }
152
+ let data = image.pngData()
153
+ DispatchQueue.main.async {
154
+ guard flight.diskGeneration == self.diskGeneration, let data, data.count <= 8 * 1024 * 1024 else {
155
+ self.pendingPersistenceBytes -= cost; return
156
+ }
157
+ // Writes and clears share this queue, closing the generation-check/write race.
158
+ self.io.async {
159
+ self.cache.storeImageData(toDisk: data, forKey: flight.storageKey)
160
+ self.cache.deleteOldFiles(completionBlock: nil)
161
+ DispatchQueue.main.async { self.pendingPersistenceBytes -= cost }
162
+ }
163
+ }
164
+ }
165
+ }
166
+ public func clearMemory() {
167
+ dispatchPrecondition(condition: .onQueue(.main)); memoryGeneration &+= 1; cache.clearMemory()
168
+ }
169
+ public func clearDisk(completion: @escaping () -> Void) {
170
+ dispatchPrecondition(condition: .onQueue(.main)); diskGeneration &+= 1
171
+ io.async { [self] in
172
+ let cleared = DispatchSemaphore(value: 0)
173
+ cache.clearDisk { cleared.signal() }
174
+ cleared.wait()
175
+ DispatchQueue.main.async { completion() }
176
+ }
177
+ }
178
+ private func permitsMemory(_ policy: String) -> Bool { policy == "memory" || policy == "memory-disk" }
179
+ private func permitsDisk(_ policy: String) -> Bool { policy == "disk" || policy == "memory-disk" }
180
+ private func pump() {
181
+ while active < 2, !queue.isEmpty {
182
+ let key = queue.removeFirst()
183
+ guard let flight = flights[key], flight.ready, flight.lease == nil, let owner = flight.subscribers.first else { continue }
184
+ let lease = UUID(); flight.lease = lease; active += 1
185
+ let timeout = DispatchWorkItem { [weak self, weak flight] in
186
+ guard let self, let flight, flight.lease == lease else { return }; self.finish(flight, image: nil)
187
+ }
188
+ flight.timeout = timeout; DispatchQueue.main.asyncAfter(deadline: .now() + 10, execute: timeout); owner.extract(lease)
189
+ }
190
+ }
191
+ private func finish(_ flight: Flight, image: UIImage?) {
192
+ guard flights[flight.key] === flight else { return }
193
+ flight.lookupWorkItem?.cancel()
194
+ flights.removeValue(forKey: flight.key); queue.removeAll { $0 == flight.key }
195
+ if flight.lease != nil { active -= 1; flight.subscribers.first?.revoked() }
196
+ flight.timeout?.cancel(); flight.lease = nil
197
+ let subscribers = flight.subscribers; flight.subscribers = []
198
+ for subscriber in subscribers where !subscriber.cancelled { if let image { subscriber.image(image) } else { subscriber.failure() } }
199
+ pump()
200
+ }
201
+ }
@@ -0,0 +1,90 @@
1
+ import UIKit
2
+ import SDWebImage
3
+ import XCTest
4
+ @testable import OneKeyImage
5
+
6
+ @MainActor
7
+ final class OneKeyMediaPreviewCacheTests: XCTestCase {
8
+ private func waitFor(_ condition: () -> Bool) {
9
+ let deadline = Date().addingTimeInterval(3)
10
+ while !condition(), Date() < deadline { RunLoop.main.run(until: Date().addingTimeInterval(0.01)) }
11
+ XCTAssertTrue(condition())
12
+ }
13
+ private func still() -> UIImage {
14
+ let format = UIGraphicsImageRendererFormat(); format.scale = 1
15
+ return UIGraphicsImageRenderer(size: CGSize(width: 32, height: 16), format: format).image { context in
16
+ UIColor.red.setFill(); context.fill(CGRect(x: 0, y: 0, width: 32, height: 16))
17
+ }
18
+ }
19
+ private func request(_ cache: OneKeyMediaPreviewCache, uri: String = "test://video", policy: String = "memory-disk",
20
+ image: @escaping (UIImage) -> Void = { _ in }, extract: @escaping (UUID) -> Void = { _ in },
21
+ revoked: @escaping () -> Void = {}) -> OneKeyMediaPreviewCache.Subscription {
22
+ cache.request(uri: uri, headers: [:], edge: 128, fit: "contain", policy: policy,
23
+ onImage: image, onExtract: extract, onRevoked: revoked, onFailure: { XCTFail("Unexpected failure") })
24
+ }
25
+ func testColdDeduplicationMemoryAndDiskReuse() {
26
+ let namespace = "media-preview-test-\(UUID().uuidString)"
27
+ let cache = OneKeyMediaPreviewCache(namespace: namespace)
28
+ var extracts = 0, delivered = 0
29
+ _ = request(cache, image: { _ in delivered += 1 }, extract: { lease in
30
+ extracts += 1; cache.complete(lease, image: self.still())
31
+ })
32
+ _ = request(cache, image: { _ in delivered += 1 }, extract: { _ in extracts += 1 })
33
+ waitFor { delivered == 2 }; XCTAssertEqual(extracts, 1)
34
+ _ = request(cache, image: { _ in delivered += 1 }, extract: { _ in XCTFail("Memory miss") })
35
+ waitFor { delivered == 3 }
36
+ let diskProbe = SDImageCache(namespace: namespace)
37
+ let key = OneKeyMediaPreviewCache.storageKey(uri: "test://video", headers: [:], edge: 128, fit: "contain")
38
+ let path = diskProbe.cachePath(forKey: key)!
39
+ waitFor { FileManager.default.fileExists(atPath: path) }
40
+ let fresh = OneKeyMediaPreviewCache(namespace: namespace)
41
+ _ = request(fresh, image: { image in
42
+ XCTAssertEqual(image.size.width / image.size.height, 2); delivered += 1
43
+ }, extract: { _ in XCTFail("Disk miss after replacing service") })
44
+ waitFor { delivered == 4 }
45
+ var cleared = false; fresh.clearDisk { cleared = true }; waitFor { cleared }
46
+ }
47
+ func testHeaderIdentityAndOwnerTransferRejectLateCompletion() {
48
+ XCTAssertEqual(OneKeyMediaPreviewCache.storageKey(uri: "u", headers: ["A": "1", "B": "2"], edge: 128, fit: "contain"),
49
+ OneKeyMediaPreviewCache.storageKey(uri: "u", headers: ["b": "2", "a": "1"], edge: 128, fit: "contain"))
50
+ XCTAssertNotEqual(OneKeyMediaPreviewCache.storageKey(uri: "u", headers: ["A": "1"], edge: 128, fit: "contain"),
51
+ OneKeyMediaPreviewCache.storageKey(uri: "u", headers: ["A": "2"], edge: 128, fit: "contain"))
52
+ let cache = OneKeyMediaPreviewCache(namespace: "transfer-\(UUID().uuidString)")
53
+ var old: UUID?, next: UUID?, deliveries = 0, revoked = 0
54
+ let a = request(cache, policy: "none", image: { _ in XCTFail("Cancelled owner") }, extract: { old = $0 }, revoked: { revoked += 1 })
55
+ _ = request(cache, policy: "none", image: { _ in deliveries += 1 }, extract: { next = $0 })
56
+ waitFor { old != nil }; cache.cancel(a); waitFor { next != nil }; XCTAssertEqual(revoked, 1)
57
+ cache.complete(old!, image: still()); XCTAssertEqual(deliveries, 0)
58
+ cache.complete(next!, image: still()); waitFor { deliveries == 1 }
59
+ }
60
+ func testTwoPermitsFIFOAndClearBlocksOldFill() {
61
+ let cache = OneKeyMediaPreviewCache(namespace: "bounds-\(UUID().uuidString)")
62
+ var leases: [UUID] = [], finished = 0
63
+ for id in 0..<3 {
64
+ _ = request(cache, uri: "test://\(id)", image: { _ in finished += 1 }, extract: { leases.append($0) })
65
+ }
66
+ waitFor { leases.count == 2 }; XCTAssertEqual(leases.count, 2)
67
+ cache.clearMemory()
68
+ var cleared = false; cache.clearDisk { cleared = true }; waitFor { cleared }
69
+ cache.complete(leases[0], image: still()); waitFor { leases.count == 3 }
70
+ cache.complete(leases[1], image: still()); cache.complete(leases[2], image: still()); waitFor { finished == 3 }
71
+ var missed = false
72
+ let probe = request(cache, uri: "test://0", extract: { _ in missed = true })
73
+ waitFor { missed }; cache.cancel(probe)
74
+ }
75
+ func testCancelledCapacityRejectionDoesNotDeliverFailure() {
76
+ let cache = OneKeyMediaPreviewCache(namespace: "capacity-\(UUID().uuidString)")
77
+ var subscriptions: [OneKeyMediaPreviewCache.Subscription] = []
78
+ for id in 0..<130 {
79
+ subscriptions.append(request(cache, uri: "test://capacity/\(id)", policy: "none"))
80
+ }
81
+ var failed = false
82
+ let rejected = cache.request(uri: "test://rejected", headers: [:], edge: 128, fit: "contain", policy: "none",
83
+ onImage: { _ in XCTFail() }, onExtract: { _ in XCTFail() }, onRevoked: {}, onFailure: { failed = true })
84
+ cache.cancel(rejected)
85
+ subscriptions.forEach { cache.cancel($0) }
86
+ RunLoop.main.run(until: Date().addingTimeInterval(0.05))
87
+ XCTAssertFalse(failed)
88
+ }
89
+
90
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/react-native-image",
3
- "version": "6.7.0-alpha.464",
3
+ "version": "6.7.0-alpha.475",
4
4
  "description": "High-performance native image view for OneKey",
5
5
  "main": "./lib/module/index.js",
6
6
  "types": "./lib/typescript/src/index.d.ts",