@onekeyfe/react-native-image 6.7.0-4 → 6.7.0-41

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 (101) hide show
  1. package/OneKeyImage.podspec +1 -1
  2. package/README.md +12 -0
  3. package/android/build.gradle +3 -1
  4. package/android/src/main/AndroidManifest.xml +7 -1
  5. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyBlockieAvatarLoader.kt +1 -1
  6. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyIcon.kt +93 -0
  7. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageCache.kt +12 -0
  8. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageGlideModule.kt +17 -0
  9. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageGlideRegistry.kt +19 -1
  10. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImagePackage.kt +2 -1
  11. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageSafety.kt +1 -1
  12. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyMediaPreviewCache.kt +199 -0
  13. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyNamedSVG.kt +217 -0
  14. package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeySVG.kt +264 -0
  15. package/android/src/test/java/com/margelo/nitro/onekeyimage/OneKeyBlockieAvatarLoaderTest.kt +2 -1
  16. package/android/src/test/java/com/margelo/nitro/onekeyimage/OneKeyImageSafetyTest.kt +1 -1
  17. package/android/src/test/java/com/margelo/nitro/onekeyimage/OneKeySVGForeignObjectTest.kt +130 -0
  18. package/ios/OneKeyAvatarImageLoader.swift +1 -1
  19. package/ios/OneKeyIcon.swift +90 -0
  20. package/ios/OneKeyImageCache.swift +23 -5
  21. package/ios/OneKeyImageCoderBridge.h +4 -0
  22. package/ios/OneKeyImageCoderBridge.m +361 -1
  23. package/ios/OneKeyImageRequestContext.swift +8 -3
  24. package/ios/OneKeyMediaPreviewCache.swift +209 -0
  25. package/ios/OneKeyNamedSVG.swift +282 -0
  26. package/ios/tests/OneKeyIconTests.swift +484 -0
  27. package/ios/tests/OneKeyImageInfrastructureTests.swift +25 -3
  28. package/ios/tests/OneKeyMediaPreviewCacheTests.swift +139 -0
  29. package/ios/tests/OneKeySVGForeignObjectTests.swift +267 -0
  30. package/lib/module/OneKeyIcon.nitro.js +4 -0
  31. package/lib/module/icon/assetUrls.js +13 -0
  32. package/lib/module/icon/dom.js +21 -0
  33. package/lib/module/icon/index.js +29 -0
  34. package/lib/module/icon/index.web.js +32 -0
  35. package/lib/module/icon/props.js +22 -0
  36. package/lib/module/package.json +6 -1
  37. package/lib/nitrogen/generated/android/c++/JHybridOneKeyIconSpec.cpp +67 -0
  38. package/lib/nitrogen/generated/android/c++/JHybridOneKeyIconSpec.hpp +66 -0
  39. package/lib/nitrogen/generated/android/c++/views/JHybridOneKeyIconStateUpdater.cpp +79 -0
  40. package/lib/nitrogen/generated/android/c++/views/JHybridOneKeyIconStateUpdater.hpp +54 -0
  41. package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/HybridOneKeyIconSpec.kt +65 -0
  42. package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/views/HybridOneKeyIconManager.kt +96 -0
  43. package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/views/HybridOneKeyIconStateUpdater.kt +23 -0
  44. package/lib/nitrogen/generated/android/onekeyimage+autolinking.cmake +4 -0
  45. package/lib/nitrogen/generated/android/onekeyimageOnLoad.cpp +18 -0
  46. package/lib/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Bridge.cpp +17 -0
  47. package/lib/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Bridge.hpp +32 -15
  48. package/lib/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Umbrella.hpp +5 -0
  49. package/lib/nitrogen/generated/ios/OneKeyImageAutolinking.mm +8 -0
  50. package/lib/nitrogen/generated/ios/OneKeyImageAutolinking.swift +12 -0
  51. package/lib/nitrogen/generated/ios/c++/HybridOneKeyIconSpecSwift.cpp +11 -0
  52. package/lib/nitrogen/generated/ios/c++/HybridOneKeyIconSpecSwift.hpp +89 -0
  53. package/lib/nitrogen/generated/ios/c++/views/HybridOneKeyIconComponent.mm +150 -0
  54. package/lib/nitrogen/generated/ios/swift/HybridOneKeyIconSpec.swift +56 -0
  55. package/lib/nitrogen/generated/ios/swift/HybridOneKeyIconSpec_cxx.swift +193 -0
  56. package/lib/nitrogen/generated/shared/c++/HybridOneKeyIconSpec.cpp +24 -0
  57. package/lib/nitrogen/generated/shared/c++/HybridOneKeyIconSpec.hpp +66 -0
  58. package/lib/nitrogen/generated/shared/c++/views/HybridOneKeyIconComponent.cpp +36 -0
  59. package/lib/nitrogen/generated/shared/c++/views/HybridOneKeyIconComponent.hpp +88 -0
  60. package/lib/nitrogen/generated/shared/json/OneKeyIconConfig.json +11 -0
  61. package/lib/typescript/src/OneKeyIcon.nitro.d.ts +7 -0
  62. package/lib/typescript/src/icon/assetUrls.d.ts +2 -0
  63. package/lib/typescript/src/icon/dom.d.ts +3 -0
  64. package/lib/typescript/src/icon/index.d.ts +12 -0
  65. package/lib/typescript/src/icon/index.web.d.ts +6 -0
  66. package/lib/typescript/src/icon/props.d.ts +8 -0
  67. package/lib/typescript/src/index.d.ts +1 -1
  68. package/nitro.json +10 -0
  69. package/nitrogen/generated/android/c++/JHybridOneKeyIconSpec.cpp +67 -0
  70. package/nitrogen/generated/android/c++/JHybridOneKeyIconSpec.hpp +66 -0
  71. package/nitrogen/generated/android/c++/views/JHybridOneKeyIconStateUpdater.cpp +79 -0
  72. package/nitrogen/generated/android/c++/views/JHybridOneKeyIconStateUpdater.hpp +54 -0
  73. package/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/HybridOneKeyIconSpec.kt +65 -0
  74. package/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/views/HybridOneKeyIconManager.kt +96 -0
  75. package/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/views/HybridOneKeyIconStateUpdater.kt +23 -0
  76. package/nitrogen/generated/android/onekeyimage+autolinking.cmake +4 -0
  77. package/nitrogen/generated/android/onekeyimageOnLoad.cpp +18 -0
  78. package/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Bridge.cpp +17 -0
  79. package/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Bridge.hpp +32 -15
  80. package/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Umbrella.hpp +5 -0
  81. package/nitrogen/generated/ios/OneKeyImageAutolinking.mm +8 -0
  82. package/nitrogen/generated/ios/OneKeyImageAutolinking.swift +12 -0
  83. package/nitrogen/generated/ios/c++/HybridOneKeyIconSpecSwift.cpp +11 -0
  84. package/nitrogen/generated/ios/c++/HybridOneKeyIconSpecSwift.hpp +89 -0
  85. package/nitrogen/generated/ios/c++/views/HybridOneKeyIconComponent.mm +150 -0
  86. package/nitrogen/generated/ios/swift/HybridOneKeyIconSpec.swift +56 -0
  87. package/nitrogen/generated/ios/swift/HybridOneKeyIconSpec_cxx.swift +193 -0
  88. package/nitrogen/generated/shared/c++/HybridOneKeyIconSpec.cpp +24 -0
  89. package/nitrogen/generated/shared/c++/HybridOneKeyIconSpec.hpp +66 -0
  90. package/nitrogen/generated/shared/c++/views/HybridOneKeyIconComponent.cpp +36 -0
  91. package/nitrogen/generated/shared/c++/views/HybridOneKeyIconComponent.hpp +88 -0
  92. package/nitrogen/generated/shared/json/OneKeyIconConfig.json +11 -0
  93. package/package.json +48 -15
  94. package/scripts/configure-icon-imports.mjs +7 -0
  95. package/scripts/icon-fixtures.test.mjs +398 -0
  96. package/src/OneKeyIcon.nitro.ts +8 -0
  97. package/src/icon/assetUrls.ts +13 -0
  98. package/src/icon/dom.ts +21 -0
  99. package/src/icon/index.tsx +38 -0
  100. package/src/icon/index.web.tsx +36 -0
  101. package/src/icon/props.ts +38 -0
@@ -21,7 +21,7 @@ Pod::Spec.new do |s|
21
21
  s.dependency "SDWebImage", "~> 5.21.7"
22
22
  s.dependency "SDWebImageSVGCoder", "~> 1.7.0"
23
23
  s.dependency "SDWebImageWebPCoder", "~> 0.14.6"
24
- s.dependency "Skeleton", package["version"]
24
+ s.dependency "Skeleton"
25
25
 
26
26
  load "nitrogen/generated/ios/OneKeyImage+autolinking.rb"
27
27
  add_nitrogen_files(s)
package/README.md CHANGED
@@ -95,3 +95,15 @@ pod 'SDWebImage', '5.21.7', :modular_headers => true
95
95
  pod 'SDWebImageWebPCoder', '0.14.6', :modular_headers => true
96
96
  pod 'SDWebImageSVGCoder', '1.7.0', :modular_headers => true
97
97
  ```
98
+
99
+ ## Named icon resource ownership
100
+
101
+ The host owns canonical SVG artwork and build output. Native builds supply a
102
+ `OneKeyIcons.bundle` on iOS and `assets/icons` on Android, including the manifest.
103
+ Web builds alias `#onekey-icon-assets` to a generated module exporting
104
+ `iconResourceHref(name: string): string | undefined`; the default SDK provider
105
+ is empty. `OneKeyIcon` props are unchanged. See [the resource contract](docs/SPEC.md#16-host-owned-icon-resources--implemented-sdk-fixture-runtime-verified).
106
+
107
+ The SDK example carries 63 independent test samples. `icons:check` and
108
+ `icons:test` are repository maintenance commands that require the example
109
+ fixtures; npm consumers do not receive those samples or the complete catalog.
@@ -63,7 +63,9 @@ android {
63
63
  targetCompatibility JavaVersion.VERSION_1_8
64
64
  }
65
65
  sourceSets {
66
- main { java.srcDirs += ["generated/java", "generated/jni"] }
66
+ main {
67
+ java.srcDirs += ["generated/java", "generated/jni"]
68
+ }
67
69
  }
68
70
  }
69
71
 
@@ -1 +1,7 @@
1
- <manifest xmlns:android="http://schemas.android.com/apk/res/android" />
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <application>
3
+ <meta-data
4
+ android:name="com.margelo.nitro.onekeyimage.OneKeyImageGlideModule"
5
+ android:value="GlideModule" />
6
+ </application>
7
+ </manifest>
@@ -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)
@@ -0,0 +1,93 @@
1
+ package com.margelo.nitro.onekeyimage
2
+
3
+ import android.content.Context
4
+ import android.content.res.Configuration
5
+ import android.graphics.PorterDuff
6
+ import android.graphics.PorterDuffColorFilter
7
+ import android.widget.ImageView
8
+ import com.facebook.react.uimanager.ThemedReactContext
9
+ import com.margelo.nitro.views.RecyclableView
10
+ import java.lang.ref.WeakReference
11
+
12
+ private class OneKeyIconHost(context: Context) : ImageView(context) {
13
+ var changed: (() -> Unit)? = null
14
+ var attached = false
15
+ private set
16
+ init { scaleType = ScaleType.FIT_CENTER }
17
+ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
18
+ super.onSizeChanged(w, h, oldw, oldh)
19
+ changed?.invoke()
20
+ }
21
+ override fun onAttachedToWindow() { super.onAttachedToWindow(); attached = true; changed?.invoke() }
22
+ override fun onDetachedFromWindow() { attached = false; super.onDetachedFromWindow(); changed?.invoke() }
23
+ override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig); changed?.invoke() }
24
+ }
25
+
26
+ class HybridOneKeyIcon(context: ThemedReactContext) : HybridOneKeyIconSpec(), RecyclableView {
27
+ private val host = OneKeyIconHost(context)
28
+ private val owner = Any()
29
+ private var generation = 0L
30
+ private var identity: String? = null
31
+ private var displayedGeometry: String? = null
32
+ private var displayed: OneKeyNamedSVG.RenderResult? = null
33
+ override val view: ImageView get() = host
34
+ override var iconName: String? = null
35
+ override var resolvedColor: String? = null
36
+ init { host.changed = { refresh() } }
37
+
38
+ override fun afterUpdate() { super.afterUpdate(); refresh() }
39
+
40
+ private fun clearImage() {
41
+ displayed = null; displayedGeometry = null
42
+ host.colorFilter = null; host.setImageDrawable(null)
43
+ }
44
+
45
+ private fun applyTint(result: OneKeyNamedSVG.RenderResult, color: String) {
46
+ host.colorFilter = result.tintColor(color)?.let { PorterDuffColorFilter(it, PorterDuff.Mode.SRC_IN) }
47
+ }
48
+
49
+ private fun refresh() {
50
+ val scale = host.resources.displayMetrics.density
51
+ val next = "$iconName|$resolvedColor|${host.width}|${host.height}|$scale|${host.attached}"
52
+ if (identity == next) return
53
+ identity = next; generation++
54
+ val revision = generation
55
+ OneKeyNamedSVG.cancel(owner)
56
+ val name = iconName
57
+ val color = resolvedColor
58
+ if (!host.attached || host.width !in 1..4096 || host.height !in 1..4096 ||
59
+ host.width.toLong() * host.height > 4194304 || name.isNullOrEmpty() || color == null ||
60
+ !OneKeyNamedSVG.isValidColor(color)) { clearImage(); return }
61
+ val geometry = "$name|${host.width}|${host.height}|$scale"
62
+ val ready = displayed
63
+ if (displayedGeometry == geometry && ready != null && host.drawable != null) {
64
+ if (ready.canTint(color)) { applyTint(ready, color); return }
65
+ } else clearImage()
66
+ OneKeyNamedSVG.cachedRender(name, color, host.width, host.height, scale)?.let { hit ->
67
+ displayed = hit; displayedGeometry = geometry
68
+ applyTint(hit, color)
69
+ host.setImageBitmap(hit.bitmap)
70
+ return
71
+ }
72
+ val weakHost = WeakReference(host)
73
+ val weakSelf = WeakReference(this)
74
+ OneKeyNamedSVG.requestRender(owner, host.context.applicationContext.assets, name, color,
75
+ host.width, host.height, scale) { result ->
76
+ val current = weakSelf.get()
77
+ val target = weakHost.get()
78
+ if (current?.generation != revision || target?.attached != true) return@requestRender
79
+ if (result == null) { current.clearImage(); return@requestRender }
80
+ current.displayed = result; current.displayedGeometry = geometry
81
+ current.applyTint(result, color)
82
+ target.setImageBitmap(result.bitmap)
83
+ }
84
+ }
85
+
86
+ override fun prepareForRecycle() {
87
+ iconName = null
88
+ resolvedColor = null
89
+ refresh()
90
+ }
91
+ override fun onDropView() { prepareForRecycle(); super.onDropView() }
92
+ override fun dispose() { prepareForRecycle(); host.changed = null; super.dispose() }
93
+ }
@@ -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
 
@@ -0,0 +1,17 @@
1
+ package com.margelo.nitro.onekeyimage
2
+
3
+ import android.content.Context
4
+ import com.bumptech.glide.Glide
5
+ import com.bumptech.glide.GlideBuilder
6
+ import com.bumptech.glide.Registry
7
+ import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
8
+ import com.bumptech.glide.module.GlideModule
9
+
10
+ @Suppress("DEPRECATION")
11
+ class OneKeyImageGlideModule : GlideModule {
12
+ override fun applyOptions(context: Context, builder: GlideBuilder) {
13
+ builder.setDiskCache(InternalCacheDiskCacheFactory(context, 320L * 1024 * 1024))
14
+ }
15
+
16
+ override fun registerComponents(context: Context, glide: Glide, registry: Registry) {}
17
+ }
@@ -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
 
@@ -266,7 +284,7 @@ private class OneKeySvgDecoder : ResourceDecoder<InputStream, SVG> {
266
284
  options: Options,
267
285
  ): Resource<SVG> {
268
286
  val svg = try {
269
- SVG.getFromInputStream(source)
287
+ OneKeySVG.parse(source)
270
288
  } catch (error: SVGParseException) {
271
289
  throw IOException("Cannot decode SVG", error)
272
290
  }
@@ -5,6 +5,7 @@ import com.facebook.react.bridge.NativeModule
5
5
  import com.facebook.react.bridge.ReactApplicationContext
6
6
  import com.facebook.react.module.model.ReactModuleInfoProvider
7
7
  import com.facebook.react.uimanager.ViewManager
8
+ import com.margelo.nitro.onekeyimage.views.HybridOneKeyIconManager
8
9
  import com.margelo.nitro.onekeyimage.views.HybridOneKeyImageManager
9
10
 
10
11
  class OneKeyImagePackage : BaseReactPackage() {
@@ -17,7 +18,7 @@ class OneKeyImagePackage : BaseReactPackage() {
17
18
  reactContext: ReactApplicationContext,
18
19
  ): List<ViewManager<*, *>> {
19
20
  OneKeyImageGlideRegistry.ensureRegistered(reactContext)
20
- return listOf(HybridOneKeyImageManager())
21
+ return listOf(HybridOneKeyImageManager(), HybridOneKeyIconManager())
21
22
  }
22
23
 
23
24
  companion object {
@@ -802,7 +802,7 @@ internal class OneKeyImageSafetyVersionedKey(
802
802
  override fun hashCode(): Int = 31 * delegate.hashCode() + CACHE_VERSION.hashCode()
803
803
 
804
804
  companion object {
805
- internal const val CACHE_VERSION = "onekey-image-safety-v2"
805
+ internal const val CACHE_VERSION = "onekey-image-safety-v4"
806
806
  private val VERSION_BYTES = CACHE_VERSION.toByteArray(Key.CHARSET)
807
807
  }
808
808
  }
@@ -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, 128L * 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
+ }