@onekeyfe/react-native-image 6.7.0-5 → 6.7.0-50
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/OneKeyImage.podspec +1 -1
- package/README.md +147 -77
- package/android/build.gradle +3 -1
- package/android/src/main/AndroidManifest.xml +7 -1
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyBlockieAvatarLoader.kt +1 -1
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyIcon.kt +93 -0
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageCache.kt +12 -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 +19 -1
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImagePackage.kt +2 -1
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyImageSafety.kt +1 -1
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyMediaPreviewCache.kt +199 -0
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeyNamedSVG.kt +217 -0
- package/android/src/main/java/com/margelo/nitro/onekeyimage/OneKeySVG.kt +264 -0
- package/android/src/test/java/com/margelo/nitro/onekeyimage/OneKeyBlockieAvatarLoaderTest.kt +2 -1
- package/android/src/test/java/com/margelo/nitro/onekeyimage/OneKeyImageSafetyTest.kt +1 -1
- package/android/src/test/java/com/margelo/nitro/onekeyimage/OneKeySVGForeignObjectTest.kt +130 -0
- package/ios/OneKeyAvatarImageLoader.swift +1 -1
- package/ios/OneKeyIcon.swift +90 -0
- package/ios/OneKeyImage.swift +8 -1
- package/ios/OneKeyImageCache.swift +23 -5
- package/ios/OneKeyImageCoderBridge.h +4 -0
- package/ios/OneKeyImageCoderBridge.m +361 -1
- package/ios/OneKeyImageRequestContext.swift +8 -3
- package/ios/OneKeyMediaPreviewCache.swift +209 -0
- package/ios/OneKeyNamedSVG.swift +314 -0
- package/ios/tests/OneKeyIconTests.swift +518 -0
- package/ios/tests/OneKeyImageInfrastructureTests.swift +25 -3
- package/ios/tests/OneKeyMediaPreviewCacheTests.swift +139 -0
- package/ios/tests/OneKeySVGForeignObjectTests.swift +267 -0
- package/lib/module/OneKeyIcon.nitro.js +4 -0
- package/lib/module/icon/assetUrls.js +13 -0
- package/lib/module/icon/dom.js +21 -0
- package/lib/module/icon/index.js +29 -0
- package/lib/module/icon/index.web.js +32 -0
- package/lib/module/icon/props.js +22 -0
- package/lib/module/package.json +6 -1
- package/lib/nitrogen/generated/android/c++/JHybridOneKeyIconSpec.cpp +67 -0
- package/lib/nitrogen/generated/android/c++/JHybridOneKeyIconSpec.hpp +66 -0
- package/lib/nitrogen/generated/android/c++/views/JHybridOneKeyIconStateUpdater.cpp +79 -0
- package/lib/nitrogen/generated/android/c++/views/JHybridOneKeyIconStateUpdater.hpp +54 -0
- package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/HybridOneKeyIconSpec.kt +65 -0
- package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/views/HybridOneKeyIconManager.kt +96 -0
- package/lib/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/views/HybridOneKeyIconStateUpdater.kt +23 -0
- package/lib/nitrogen/generated/android/onekeyimage+autolinking.cmake +4 -0
- package/lib/nitrogen/generated/android/onekeyimageOnLoad.cpp +18 -0
- package/lib/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Bridge.cpp +17 -0
- package/lib/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Bridge.hpp +32 -15
- package/lib/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Umbrella.hpp +5 -0
- package/lib/nitrogen/generated/ios/OneKeyImageAutolinking.mm +8 -0
- package/lib/nitrogen/generated/ios/OneKeyImageAutolinking.swift +12 -0
- package/lib/nitrogen/generated/ios/c++/HybridOneKeyIconSpecSwift.cpp +11 -0
- package/lib/nitrogen/generated/ios/c++/HybridOneKeyIconSpecSwift.hpp +89 -0
- package/lib/nitrogen/generated/ios/c++/views/HybridOneKeyIconComponent.mm +150 -0
- package/lib/nitrogen/generated/ios/swift/HybridOneKeyIconSpec.swift +56 -0
- package/lib/nitrogen/generated/ios/swift/HybridOneKeyIconSpec_cxx.swift +193 -0
- package/lib/nitrogen/generated/shared/c++/HybridOneKeyIconSpec.cpp +24 -0
- package/lib/nitrogen/generated/shared/c++/HybridOneKeyIconSpec.hpp +66 -0
- package/lib/nitrogen/generated/shared/c++/views/HybridOneKeyIconComponent.cpp +36 -0
- package/lib/nitrogen/generated/shared/c++/views/HybridOneKeyIconComponent.hpp +88 -0
- package/lib/nitrogen/generated/shared/json/OneKeyIconConfig.json +11 -0
- package/lib/typescript/src/OneKeyIcon.nitro.d.ts +7 -0
- package/lib/typescript/src/icon/assetUrls.d.ts +2 -0
- package/lib/typescript/src/icon/dom.d.ts +3 -0
- package/lib/typescript/src/icon/index.d.ts +12 -0
- package/lib/typescript/src/icon/index.web.d.ts +6 -0
- package/lib/typescript/src/icon/props.d.ts +8 -0
- package/lib/typescript/src/index.d.ts +1 -1
- package/nitro.json +10 -0
- package/nitrogen/generated/android/c++/JHybridOneKeyIconSpec.cpp +67 -0
- package/nitrogen/generated/android/c++/JHybridOneKeyIconSpec.hpp +66 -0
- package/nitrogen/generated/android/c++/views/JHybridOneKeyIconStateUpdater.cpp +79 -0
- package/nitrogen/generated/android/c++/views/JHybridOneKeyIconStateUpdater.hpp +54 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/HybridOneKeyIconSpec.kt +65 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/views/HybridOneKeyIconManager.kt +96 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/onekeyimage/views/HybridOneKeyIconStateUpdater.kt +23 -0
- package/nitrogen/generated/android/onekeyimage+autolinking.cmake +4 -0
- package/nitrogen/generated/android/onekeyimageOnLoad.cpp +18 -0
- package/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Bridge.cpp +17 -0
- package/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Bridge.hpp +32 -15
- package/nitrogen/generated/ios/OneKeyImage-Swift-Cxx-Umbrella.hpp +5 -0
- package/nitrogen/generated/ios/OneKeyImageAutolinking.mm +8 -0
- package/nitrogen/generated/ios/OneKeyImageAutolinking.swift +12 -0
- package/nitrogen/generated/ios/c++/HybridOneKeyIconSpecSwift.cpp +11 -0
- package/nitrogen/generated/ios/c++/HybridOneKeyIconSpecSwift.hpp +89 -0
- package/nitrogen/generated/ios/c++/views/HybridOneKeyIconComponent.mm +150 -0
- package/nitrogen/generated/ios/swift/HybridOneKeyIconSpec.swift +56 -0
- package/nitrogen/generated/ios/swift/HybridOneKeyIconSpec_cxx.swift +193 -0
- package/nitrogen/generated/shared/c++/HybridOneKeyIconSpec.cpp +24 -0
- package/nitrogen/generated/shared/c++/HybridOneKeyIconSpec.hpp +66 -0
- package/nitrogen/generated/shared/c++/views/HybridOneKeyIconComponent.cpp +36 -0
- package/nitrogen/generated/shared/c++/views/HybridOneKeyIconComponent.hpp +88 -0
- package/nitrogen/generated/shared/json/OneKeyIconConfig.json +11 -0
- package/package.json +48 -15
- package/scripts/configure-icon-imports.mjs +7 -0
- package/scripts/icon-fixtures.test.mjs +398 -0
- package/src/OneKeyIcon.nitro.ts +8 -0
- package/src/icon/assetUrls.ts +13 -0
- package/src/icon/dom.ts +21 -0
- package/src/icon/index.tsx +38 -0
- package/src/icon/index.web.tsx +36 -0
- package/src/icon/props.ts +38 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
package com.margelo.nitro.onekeyimage
|
|
2
|
+
|
|
3
|
+
import android.content.res.AssetManager
|
|
4
|
+
import android.graphics.Bitmap
|
|
5
|
+
import android.graphics.Canvas
|
|
6
|
+
import android.graphics.Color
|
|
7
|
+
import android.graphics.Paint
|
|
8
|
+
import android.graphics.PorterDuff
|
|
9
|
+
import android.graphics.PorterDuffColorFilter
|
|
10
|
+
import android.os.Handler
|
|
11
|
+
import android.os.Looper
|
|
12
|
+
import android.util.Log
|
|
13
|
+
import org.json.JSONObject
|
|
14
|
+
import java.util.concurrent.Executors
|
|
15
|
+
import kotlin.math.roundToInt
|
|
16
|
+
|
|
17
|
+
/** Process-owned named resources; no React runtime or Activity is retained. */
|
|
18
|
+
object OneKeyNamedSVG {
|
|
19
|
+
enum class RecolorMode { FIXED, SINGLE, MULTIPLE, RASTER }
|
|
20
|
+
data class IconMetadata(
|
|
21
|
+
val width: Float,
|
|
22
|
+
val height: Float,
|
|
23
|
+
val mode: RecolorMode,
|
|
24
|
+
)
|
|
25
|
+
data class RenderResult(val bitmap: Bitmap, val mode: RecolorMode,
|
|
26
|
+
val sourceIdentity: String, val maskAlpha: Int) {
|
|
27
|
+
fun canTint(color: String): Boolean {
|
|
28
|
+
val value = parseColor(color) ?: return false
|
|
29
|
+
return mode == RecolorMode.FIXED || mode == RecolorMode.SINGLE ||
|
|
30
|
+
(mode == RecolorMode.MULTIPLE && Color.alpha(value) == maskAlpha)
|
|
31
|
+
}
|
|
32
|
+
fun tintColor(color: String): Int? {
|
|
33
|
+
val value = parseColor(color) ?: return null
|
|
34
|
+
return when(mode) {
|
|
35
|
+
RecolorMode.SINGLE -> value
|
|
36
|
+
RecolorMode.MULTIPLE -> value or (0xff shl 24)
|
|
37
|
+
else -> null
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
internal fun finalBitmap(color: String): Bitmap {
|
|
41
|
+
val tint = tintColor(color) ?: return bitmap
|
|
42
|
+
if (tint == Color.BLACK) return bitmap
|
|
43
|
+
val output = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)
|
|
44
|
+
val paint = Paint().apply { colorFilter = PorterDuffColorFilter(tint, PorterDuff.Mode.SRC_IN) }
|
|
45
|
+
Canvas(output).drawBitmap(bitmap, 0f, 0f, paint)
|
|
46
|
+
return output
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
private data class Request(val assets: AssetManager, val name: String, val color: String,
|
|
51
|
+
val width: Int, val height: Int, val scale: Float, val finalColor: Boolean, val complete: (RenderResult?) -> Unit)
|
|
52
|
+
private val lock = Any()
|
|
53
|
+
private val pending = LinkedHashMap<Any, Request>()
|
|
54
|
+
private val cache = LinkedHashMap<String, RenderResult>(128, 0.75f, true)
|
|
55
|
+
private var cacheBytes = 0L
|
|
56
|
+
private var activeWorkers = 0
|
|
57
|
+
private var manifest: JSONObject? = null
|
|
58
|
+
private val manifestLock = Any()
|
|
59
|
+
private val workers = Executors.newFixedThreadPool(2)
|
|
60
|
+
private val main = Handler(Looper.getMainLooper())
|
|
61
|
+
private val colorPattern = Regex("rgba\\(\\d{1,3},\\d{1,3},\\d{1,3},(?:0(?:\\.\\d+)?|1(?:\\.0+)?)\\)")
|
|
62
|
+
|
|
63
|
+
private var manifestMissingLogged = false
|
|
64
|
+
|
|
65
|
+
fun cancel(owner: Any) { synchronized(lock) { pending.remove(owner) } }
|
|
66
|
+
|
|
67
|
+
/** Caller holds manifestLock. Hosts own the resources, so a miss is logged once. */
|
|
68
|
+
private fun loadManifestLocked(assets: AssetManager): JSONObject? {
|
|
69
|
+
manifest?.let { return it }
|
|
70
|
+
return try {
|
|
71
|
+
assets.open("icons/manifest.json").bufferedReader().use { JSONObject(it.readText()) }
|
|
72
|
+
.also { manifest = it }
|
|
73
|
+
} catch (error: Exception) {
|
|
74
|
+
if (!manifestMissingLogged) {
|
|
75
|
+
manifestMissingLogged = true
|
|
76
|
+
Log.w("OneKeyIcon", "assets/icons/manifest.json is missing or invalid; named icons will not render", error)
|
|
77
|
+
}
|
|
78
|
+
null
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
private fun modeOf(metadata: JSONObject): RecolorMode = try {
|
|
83
|
+
RecolorMode.valueOf(metadata.optString("recolorMode", "raster").uppercase())
|
|
84
|
+
} catch (_: IllegalArgumentException) {
|
|
85
|
+
RecolorMode.RASTER
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private data class RenderKey(val identity: String, val key: String, val maskAlpha: Int)
|
|
89
|
+
|
|
90
|
+
private fun renderKey(name: String, digest: String, width: Int, height: Int, scale: Float,
|
|
91
|
+
mode: RecolorMode, requestColor: String, color: Int): RenderKey {
|
|
92
|
+
val identity = "$name|$digest|$width|$height|$scale"
|
|
93
|
+
val maskAlpha = if (mode == RecolorMode.MULTIPLE) Color.alpha(color) else 255
|
|
94
|
+
val colorKey = when(mode) {
|
|
95
|
+
RecolorMode.RASTER -> requestColor
|
|
96
|
+
RecolorMode.MULTIPLE -> maskAlpha.toString()
|
|
97
|
+
else -> ""
|
|
98
|
+
}
|
|
99
|
+
return RenderKey(identity, "$identity|$mode|$colorKey", maskAlpha)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Main-thread fast path: returns an already-decoded result without asset I/O or
|
|
104
|
+
* manifest loading, so remounted and recycled views paint in the same frame.
|
|
105
|
+
*/
|
|
106
|
+
fun cachedRender(name: String, color: String, width: Int, height: Int, scale: Float): RenderResult? {
|
|
107
|
+
val value = parseColor(color) ?: return null
|
|
108
|
+
val metadata = synchronized(manifestLock) { manifest?.optJSONObject(name) } ?: return null
|
|
109
|
+
val digest = metadata.optString("digest").takeIf { it.isNotEmpty() } ?: return null
|
|
110
|
+
val key = renderKey(name, digest, width, height, scale, modeOf(metadata), color, value).key
|
|
111
|
+
return synchronized(lock) { cache[key] }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
fun iconMetadata(assets: AssetManager, name: String): IconMetadata? {
|
|
115
|
+
val trimmed = name.trim()
|
|
116
|
+
if (trimmed.isEmpty()) return null
|
|
117
|
+
val metadata = try {
|
|
118
|
+
synchronized(manifestLock) {
|
|
119
|
+
loadManifestLocked(assets)?.optJSONObject(trimmed)
|
|
120
|
+
}
|
|
121
|
+
} catch (_: Exception) {
|
|
122
|
+
null
|
|
123
|
+
} ?: return null
|
|
124
|
+
val mode = modeOf(metadata)
|
|
125
|
+
val viewBox = metadata.optJSONArray("viewBox")
|
|
126
|
+
val vbWidth = if (viewBox != null && viewBox.length() >= 4) viewBox.optDouble(2, 24.0).toFloat() else 24f
|
|
127
|
+
val vbHeight = if (viewBox != null && viewBox.length() >= 4) viewBox.optDouble(3, 24.0).toFloat() else 24f
|
|
128
|
+
val width = if (vbWidth > 0f) vbWidth else 24f
|
|
129
|
+
val height = if (vbHeight > 0f) vbHeight else 24f
|
|
130
|
+
return IconMetadata(width = width, height = height, mode = mode)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
fun request(owner: Any, assets: AssetManager, name: String, color: String,
|
|
134
|
+
width: Int, height: Int, scale: Float, complete: (Bitmap?) -> Unit) {
|
|
135
|
+
enqueue(owner, assets, name, color, width, height, scale, true) { complete(it?.bitmap) }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
fun requestRender(owner: Any, assets: AssetManager, name: String, color: String,
|
|
139
|
+
width: Int, height: Int, scale: Float, complete: (RenderResult?) -> Unit) {
|
|
140
|
+
enqueue(owner, assets, name, color, width, height, scale, false, complete)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
private fun enqueue(owner: Any, assets: AssetManager, name: String, color: String,
|
|
144
|
+
width: Int, height: Int, scale: Float, finalColor: Boolean, complete: (RenderResult?) -> Unit) {
|
|
145
|
+
synchronized(lock) {
|
|
146
|
+
pending[owner] = Request(assets, name, color, width, height, scale, finalColor, complete)
|
|
147
|
+
while (activeWorkers < 2 && activeWorkers < pending.size) {
|
|
148
|
+
activeWorkers++
|
|
149
|
+
workers.execute { drain() }
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
private fun parseColor(color: String): Int? {
|
|
155
|
+
if (!colorPattern.matches(color)) return null
|
|
156
|
+
val channels = color.removePrefix("rgba(").removeSuffix(")").split(',')
|
|
157
|
+
val rgb = channels.take(3).map { it.toInt() }
|
|
158
|
+
if (rgb.any { it !in 0..255 }) return null
|
|
159
|
+
val alpha = (channels[3].toDouble() * 255).roundToInt()
|
|
160
|
+
return Color.argb(alpha, rgb[0], rgb[1], rgb[2])
|
|
161
|
+
}
|
|
162
|
+
fun isValidColor(color: String): Boolean = parseColor(color) != null
|
|
163
|
+
|
|
164
|
+
private fun drain() {
|
|
165
|
+
while (true) {
|
|
166
|
+
val request = synchronized(lock) {
|
|
167
|
+
val first = pending.entries.firstOrNull()
|
|
168
|
+
if (first == null) { activeWorkers--; null }
|
|
169
|
+
else { pending.remove(first.key); first.value }
|
|
170
|
+
} ?: return
|
|
171
|
+
val bitmap = try {
|
|
172
|
+
decode(request)?.let { result ->
|
|
173
|
+
if (request.finalColor) result.copy(bitmap = result.finalBitmap(request.color), mode = RecolorMode.RASTER)
|
|
174
|
+
else result
|
|
175
|
+
}
|
|
176
|
+
} catch (_: Throwable) { null } // OOM must not strand activeWorkers.
|
|
177
|
+
main.post { request.complete(bitmap) }
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
private fun decode(request: Request): RenderResult? {
|
|
182
|
+
if (request.width !in 1..4096 || request.height !in 1..4096 ||
|
|
183
|
+
request.width.toLong() * request.height > 4194304 || !request.scale.isFinite() ||
|
|
184
|
+
request.scale <= 0) return null
|
|
185
|
+
val color = parseColor(request.color) ?: return null
|
|
186
|
+
val metadata = synchronized(manifestLock) {
|
|
187
|
+
loadManifestLocked(request.assets)?.optJSONObject(request.name)
|
|
188
|
+
} ?: return null
|
|
189
|
+
val mode = modeOf(metadata)
|
|
190
|
+
val (sourceIdentity, key, maskAlpha) = renderKey(request.name, metadata.getString("digest"),
|
|
191
|
+
request.width, request.height, request.scale, mode, request.color, color)
|
|
192
|
+
val paintColor = when(mode) {
|
|
193
|
+
RecolorMode.FIXED, RecolorMode.SINGLE -> Color.BLACK
|
|
194
|
+
RecolorMode.MULTIPLE -> Color.argb(maskAlpha, 0, 0, 0)
|
|
195
|
+
RecolorMode.RASTER -> color
|
|
196
|
+
}
|
|
197
|
+
synchronized(lock) { cache[key]?.let { return it } }
|
|
198
|
+
// AndroidSVG rgba quantizes with 256; SVG hex alpha preserves the exact CSS 8-bit channel.
|
|
199
|
+
val svgColor = listOf(Color.red(paintColor), Color.green(paintColor), Color.blue(paintColor), Color.alpha(paintColor))
|
|
200
|
+
.joinToString(separator = "", prefix = "#") { it.toString(16).padStart(2, '0') }
|
|
201
|
+
val xml = request.assets.open("icons/${request.name}.svg").bufferedReader().use { it.readText() }
|
|
202
|
+
.replace(Regex("((?:fill|stroke)\\s*=\\s*[\"'])currentColor([\"'])"), "$1${svgColor}$2")
|
|
203
|
+
val bitmap = OneKeySVG.decode(xml.byteInputStream()).render(request.width, request.height)
|
|
204
|
+
val result = RenderResult(bitmap, mode, sourceIdentity, maskAlpha)
|
|
205
|
+
val bytes = bitmap.allocationByteCount.toLong()
|
|
206
|
+
if (bytes <= 8388608) synchronized(lock) {
|
|
207
|
+
cache.put(key, result)?.let { cacheBytes -= it.bitmap.allocationByteCount }
|
|
208
|
+
cacheBytes += bytes
|
|
209
|
+
while (cache.size > 128 || cacheBytes > 8388608) {
|
|
210
|
+
val first = cache.entries.first()
|
|
211
|
+
cacheBytes -= first.value.bitmap.allocationByteCount
|
|
212
|
+
cache.remove(first.key)
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return result
|
|
216
|
+
}
|
|
217
|
+
}
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
package com.margelo.nitro.onekeyimage
|
|
2
|
+
|
|
3
|
+
import android.graphics.Bitmap
|
|
4
|
+
import android.graphics.Canvas
|
|
5
|
+
import android.graphics.BitmapFactory
|
|
6
|
+
import com.caverock.androidsvg.SVG
|
|
7
|
+
import java.io.InputStream
|
|
8
|
+
import java.io.IOException
|
|
9
|
+
import java.io.StringWriter
|
|
10
|
+
import javax.xml.parsers.DocumentBuilderFactory
|
|
11
|
+
import javax.xml.parsers.SAXParserFactory
|
|
12
|
+
import javax.xml.transform.TransformerFactory
|
|
13
|
+
import javax.xml.transform.OutputKeys
|
|
14
|
+
import javax.xml.transform.dom.DOMSource
|
|
15
|
+
import javax.xml.transform.stream.StreamResult
|
|
16
|
+
import kotlin.io.encoding.Base64
|
|
17
|
+
import kotlin.io.encoding.ExperimentalEncodingApi
|
|
18
|
+
import org.w3c.dom.Element
|
|
19
|
+
import org.w3c.dom.Node
|
|
20
|
+
import org.xml.sax.SAXException
|
|
21
|
+
import org.xml.sax.Attributes
|
|
22
|
+
import org.xml.sax.helpers.DefaultHandler
|
|
23
|
+
|
|
24
|
+
/** Synchronous per-request document; loaders retain scheduling and cancellation. */
|
|
25
|
+
object OneKeySVG {
|
|
26
|
+
fun decode(source: InputStream): OneKeySVGDocument = OneKeySVGDocument(parse(source))
|
|
27
|
+
internal fun parse(source: InputStream): SVG {
|
|
28
|
+
val data = OneKeyLimitedInputStream(source).readBytes()
|
|
29
|
+
val normalized = normalize(data) { png, readPixels ->
|
|
30
|
+
val decoded = BitmapFactory.decodeByteArray(png, 0, png.size)
|
|
31
|
+
?: throw IOException("Invalid PNG in SVG foreignObject")
|
|
32
|
+
try {
|
|
33
|
+
if (readPixels) IntArray(decoded.width * decoded.height).also {
|
|
34
|
+
decoded.getPixels(it, 0, decoded.width, 0, 0, decoded.width, decoded.height)
|
|
35
|
+
} else null
|
|
36
|
+
} finally { decoded.recycle() }
|
|
37
|
+
}
|
|
38
|
+
return SVG.getFromInputStream(normalized.inputStream())
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
@OptIn(ExperimentalEncodingApi::class)
|
|
42
|
+
internal fun normalize(data: ByteArray, decodePNG: (ByteArray, Boolean) -> IntArray?): ByteArray {
|
|
43
|
+
val xml = when {
|
|
44
|
+
data.size >= 2 && ((data[0] == 0xff.toByte() && data[1] == 0xfe.toByte()) ||
|
|
45
|
+
(data[0] == 0xfe.toByte() && data[1] == 0xff.toByte())) -> String(data, Charsets.UTF_16)
|
|
46
|
+
data.size >= 4 && data[0] == '<'.code.toByte() && data[1] == 0.toByte() &&
|
|
47
|
+
data[2] != 0.toByte() && data[3] == 0.toByte() -> String(data, Charsets.UTF_16LE)
|
|
48
|
+
data.size >= 4 && data[0] == 0.toByte() && data[1] == '<'.code.toByte() &&
|
|
49
|
+
data[2] == 0.toByte() && data[3] != 0.toByte() -> String(data, Charsets.UTF_16BE)
|
|
50
|
+
else -> String(data, Charsets.UTF_8)
|
|
51
|
+
}
|
|
52
|
+
if (!xml.contains("foreignObject")) return data
|
|
53
|
+
fun unsupported(): Nothing = throw IOException("Unsupported SVG foreignObject")
|
|
54
|
+
if (data.size > 8 * 1024 * 1024 || xml.contains("<!DOCTYPE", ignoreCase = true) ||
|
|
55
|
+
xml.contains("<!ENTITY", ignoreCase = true)) unsupported()
|
|
56
|
+
var elementCount = 0
|
|
57
|
+
var elementDepth = 0
|
|
58
|
+
SAXParserFactory.newInstance().newSAXParser().parse(data.inputStream(), object : DefaultHandler() {
|
|
59
|
+
override fun startElement(uri: String?, localName: String?, qName: String?, attributes: Attributes?) {
|
|
60
|
+
if (++elementCount > 10000 || ++elementDepth > 64) unsupported()
|
|
61
|
+
}
|
|
62
|
+
override fun endElement(uri: String?, localName: String?, qName: String?) { elementDepth-- }
|
|
63
|
+
})
|
|
64
|
+
val factory = DocumentBuilderFactory.newInstance().apply {
|
|
65
|
+
isNamespaceAware = true
|
|
66
|
+
isExpandEntityReferences = false
|
|
67
|
+
}
|
|
68
|
+
val builder = factory.newDocumentBuilder()
|
|
69
|
+
builder.setEntityResolver { _, _ -> throw SAXException("External SVG entities are disabled") }
|
|
70
|
+
val document = builder.parse(data.inputStream())
|
|
71
|
+
if (document.documentElement.localName != "svg") unsupported()
|
|
72
|
+
if (document.getElementsByTagNameNS("*", "foreignObject").length == 0) return data
|
|
73
|
+
var nodes = 0
|
|
74
|
+
var objects = 0
|
|
75
|
+
var imageBytes = 0L
|
|
76
|
+
var imagePixels = 0L
|
|
77
|
+
var hasImageRendering = false
|
|
78
|
+
var nearestNeighbor = false
|
|
79
|
+
var pixelRuns = 0
|
|
80
|
+
var pathCharacters = 0
|
|
81
|
+
val allowed = setOf("x", "y", "width", "height", "transform", "opacity", "clip-path", "mask", "id")
|
|
82
|
+
val imageAllowed = setOf("xmlns", "src", "width", "height", "alt")
|
|
83
|
+
fun children(node: Node) = (0 until node.childNodes.length).map { node.childNodes.item(it) }
|
|
84
|
+
fun validateStyle(element: Element) {
|
|
85
|
+
val css = children(element).joinToString("") {
|
|
86
|
+
if (it.nodeType != Node.TEXT_NODE && it.nodeType != Node.CDATA_SECTION_NODE) unsupported()
|
|
87
|
+
it.nodeValue
|
|
88
|
+
}
|
|
89
|
+
val rule = Regex("([^{}]+)\\{([^{}]*)\\}")
|
|
90
|
+
// These selectors cannot match converted containers or generated pixel paths.
|
|
91
|
+
val svgSelectors = setOf("rect", "circle", "ellipse", "line", "polyline", "polygon", "text", "tspan", "stop")
|
|
92
|
+
var cursor = 0
|
|
93
|
+
while (cursor < css.length) {
|
|
94
|
+
val match = rule.matchAt(css, cursor) ?: run {
|
|
95
|
+
if (css.substring(cursor).isBlank()) return
|
|
96
|
+
unsupported()
|
|
97
|
+
}
|
|
98
|
+
cursor = match.range.last + 1
|
|
99
|
+
val selector = match.groupValues[1].trim()
|
|
100
|
+
if (selector.split(',').all { it.trim() in svgSelectors }) continue
|
|
101
|
+
if (selector != "img") unsupported()
|
|
102
|
+
val body = match.groupValues[2]
|
|
103
|
+
for (declaration in body.split(';').map(String::trim).filter(String::isNotEmpty)) {
|
|
104
|
+
val parts = declaration.split(':').map(String::trim)
|
|
105
|
+
if (parts.size != 2) unsupported()
|
|
106
|
+
val (key, value) = parts
|
|
107
|
+
if (key in setOf("width", "height") && value == "100%") continue
|
|
108
|
+
if (key == "image-rendering") {
|
|
109
|
+
val smooth = value in setOf("auto", "smooth", "optimizeQuality")
|
|
110
|
+
val nearest = value in setOf("optimizeSpeed", "-moz-crisp-edges",
|
|
111
|
+
"-o-crisp-edges", "-webkit-optimize-contrast", "optimize-contrast", "crisp-edges", "pixelated")
|
|
112
|
+
if (!smooth && !nearest) unsupported()
|
|
113
|
+
hasImageRendering = true
|
|
114
|
+
nearestNeighbor = nearest
|
|
115
|
+
continue
|
|
116
|
+
}
|
|
117
|
+
if (key == "-ms-interpolation-mode" && value == "nearest-neighbor") {
|
|
118
|
+
if (!hasImageRendering) nearestNeighbor = true
|
|
119
|
+
continue
|
|
120
|
+
}
|
|
121
|
+
unsupported()
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
fun collectStyles(node: Node) {
|
|
126
|
+
if (node is Element && node.localName == "style") validateStyle(node)
|
|
127
|
+
else children(node).forEach(::collectStyles)
|
|
128
|
+
}
|
|
129
|
+
collectStyles(document)
|
|
130
|
+
fun convert(node: Node, depth: Int) {
|
|
131
|
+
if (depth > 64) unsupported()
|
|
132
|
+
if (node.nodeType == Node.PROCESSING_INSTRUCTION_NODE) unsupported()
|
|
133
|
+
if (node !is Element) return
|
|
134
|
+
if (++nodes > 10000) unsupported()
|
|
135
|
+
for (key in listOf("fill", "stroke", "stop-color", "flood-color", "lighting-color", "color")) {
|
|
136
|
+
val value = node.getAttribute(key)
|
|
137
|
+
if (!Regex("#[0-9a-fA-F]{8}").matches(value)) continue
|
|
138
|
+
val rgba = value.substring(1).toLong(16)
|
|
139
|
+
val alpha = (rgba and 255) / 255.0
|
|
140
|
+
node.setAttribute(key, "rgba(${(rgba shr 24) and 255},${(rgba shr 16) and 255},${(rgba shr 8) and 255},$alpha)")
|
|
141
|
+
}
|
|
142
|
+
if (node.localName == "style") return
|
|
143
|
+
if (node.localName != "foreignObject") {
|
|
144
|
+
children(node).forEach { convert(it, depth + 1) }
|
|
145
|
+
return
|
|
146
|
+
}
|
|
147
|
+
if (++objects > 16) unsupported()
|
|
148
|
+
for (index in 0 until node.attributes.length) {
|
|
149
|
+
if (node.attributes.item(index).nodeName !in allowed) unsupported()
|
|
150
|
+
}
|
|
151
|
+
for (key in listOf("width", "height")) {
|
|
152
|
+
val number = node.getAttribute(key).toDoubleOrNull() ?: unsupported()
|
|
153
|
+
if (!number.isFinite() || number <= 0 || number > 32768) unsupported()
|
|
154
|
+
}
|
|
155
|
+
val content = children(node).filter {
|
|
156
|
+
when (it.nodeType) {
|
|
157
|
+
Node.COMMENT_NODE -> false
|
|
158
|
+
Node.TEXT_NODE, Node.CDATA_SECTION_NODE -> {
|
|
159
|
+
if (it.nodeValue.isNotBlank()) unsupported()
|
|
160
|
+
false
|
|
161
|
+
}
|
|
162
|
+
else -> true
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
val image = content.singleOrNull() as? Element ?: unsupported()
|
|
166
|
+
if (image.tagName != "img" || image.namespaceURI != "http://www.w3.org/1999/xhtml") unsupported()
|
|
167
|
+
for (index in 0 until image.attributes.length) {
|
|
168
|
+
if (image.attributes.item(index).nodeName !in imageAllowed) unsupported()
|
|
169
|
+
}
|
|
170
|
+
for (key in listOf("width", "height")) {
|
|
171
|
+
if (image.hasAttribute(key) && image.getAttribute(key) != "100%") unsupported()
|
|
172
|
+
}
|
|
173
|
+
if (children(image).any { it.nodeType != Node.TEXT_NODE || it.nodeValue.isNotBlank() }) unsupported()
|
|
174
|
+
val source = image.getAttribute("src")
|
|
175
|
+
val prefix = "data:image/png;base64,"
|
|
176
|
+
if (!source.startsWith(prefix, ignoreCase = true) || source.length - prefix.length > 11184812) unsupported()
|
|
177
|
+
val png = try { Base64.Default.decode(source.substring(prefix.length)) }
|
|
178
|
+
catch (_: IllegalArgumentException) { unsupported() }
|
|
179
|
+
imageBytes += png.size
|
|
180
|
+
if (imageBytes > 8 * 1024 * 1024 || png.size < 24 ||
|
|
181
|
+
!png.copyOfRange(0, 8).contentEquals(byteArrayOf(137.toByte(), 80, 78, 71, 13, 10, 26, 10))) unsupported()
|
|
182
|
+
val metadata = OneKeyEncodedImageInspector.inspect(png.inputStream())
|
|
183
|
+
val width = metadata.width.toLong()
|
|
184
|
+
val height = metadata.height.toLong()
|
|
185
|
+
imagePixels += width * height
|
|
186
|
+
if (metadata.animated || width <= 0 || height <= 0 || width > 8192 || height > 8192 ||
|
|
187
|
+
imagePixels > 4194304) unsupported()
|
|
188
|
+
val pixels = decodePNG(png, nearestNeighbor)
|
|
189
|
+
val replacement = document.createElementNS("http://www.w3.org/2000/svg", if (nearestNeighbor) "svg" else "image")
|
|
190
|
+
for (index in 0 until node.attributes.length) {
|
|
191
|
+
val attribute = node.attributes.item(index)
|
|
192
|
+
replacement.setAttribute(attribute.nodeName, attribute.nodeValue)
|
|
193
|
+
}
|
|
194
|
+
replacement.setAttribute("preserveAspectRatio", "none")
|
|
195
|
+
replacement.setAttribute("image-rendering", if (nearestNeighbor) "optimizeSpeed" else "optimizeQuality")
|
|
196
|
+
if (nearestNeighbor) {
|
|
197
|
+
// Paint(0) still filters bitmaps on Android Q+. Preserve pixel edges as
|
|
198
|
+
// bounded vector geometry instead of depending on the library's hint.
|
|
199
|
+
if (pixels == null || pixels.size.toLong() != width * height) unsupported()
|
|
200
|
+
val paths = linkedMapOf<Int, StringBuilder>()
|
|
201
|
+
val rasterWidth = width.toInt()
|
|
202
|
+
for (y in 0 until height.toInt()) {
|
|
203
|
+
var x = 0
|
|
204
|
+
while (x < rasterWidth) {
|
|
205
|
+
val color = pixels[y * rasterWidth + x]
|
|
206
|
+
var end = x + 1
|
|
207
|
+
while (end < rasterWidth && pixels[y * rasterWidth + end] == color) end++
|
|
208
|
+
if (color ushr 24 != 0) {
|
|
209
|
+
if (++pixelRuns > 16384) unsupported()
|
|
210
|
+
val path = paths.getOrPut(color) {
|
|
211
|
+
if (++elementCount > 10000) unsupported()
|
|
212
|
+
StringBuilder()
|
|
213
|
+
}
|
|
214
|
+
val run = "M$x ${y}h${end - x}v1H${x}z"
|
|
215
|
+
pathCharacters += run.length
|
|
216
|
+
if (pathCharacters > 512 * 1024) unsupported()
|
|
217
|
+
path.append(run)
|
|
218
|
+
}
|
|
219
|
+
x = end
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
replacement.setAttribute("viewBox", "0 0 $width $height")
|
|
223
|
+
replacement.setAttribute("overflow", "hidden")
|
|
224
|
+
for ((color, path) in paths) {
|
|
225
|
+
val shape = document.createElementNS("http://www.w3.org/2000/svg", "path")
|
|
226
|
+
shape.setAttribute("d", path.toString())
|
|
227
|
+
shape.setAttribute("stroke", "none")
|
|
228
|
+
shape.setAttribute("fill", "rgb(${(color ushr 16) and 255},${(color ushr 8) and 255},${color and 255})")
|
|
229
|
+
shape.setAttribute("fill-opacity", ((color ushr 24) / 255.0).toString())
|
|
230
|
+
replacement.appendChild(shape)
|
|
231
|
+
}
|
|
232
|
+
} else {
|
|
233
|
+
replacement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink")
|
|
234
|
+
replacement.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", prefix + source.substring(prefix.length))
|
|
235
|
+
}
|
|
236
|
+
node.parentNode.replaceChild(replacement, node)
|
|
237
|
+
}
|
|
238
|
+
children(document).forEach { convert(it, 1) }
|
|
239
|
+
val output = StringWriter()
|
|
240
|
+
TransformerFactory.newInstance().newTransformer().apply {
|
|
241
|
+
setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes")
|
|
242
|
+
}.transform(DOMSource(document), StreamResult(output))
|
|
243
|
+
return output.toString().toByteArray(Charsets.UTF_8)
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
class OneKeySVGDocument internal constructor(private val svg: SVG) {
|
|
248
|
+
val viewBoxWidth: Float? = svg.documentViewBox?.width()
|
|
249
|
+
val viewBoxHeight: Float? = svg.documentViewBox?.height()
|
|
250
|
+
val intrinsicWidth: Float = svg.documentWidth
|
|
251
|
+
val intrinsicHeight: Float = svg.documentHeight
|
|
252
|
+
|
|
253
|
+
fun render(width: Int, height: Int): Bitmap {
|
|
254
|
+
require(width > 0 && height > 0)
|
|
255
|
+
if (svg.documentViewBox == null && intrinsicWidth > 0 && intrinsicHeight > 0) {
|
|
256
|
+
svg.setDocumentViewBox(0f, 0f, intrinsicWidth, intrinsicHeight)
|
|
257
|
+
}
|
|
258
|
+
svg.setDocumentWidth(width.toFloat())
|
|
259
|
+
svg.setDocumentHeight(height.toFloat())
|
|
260
|
+
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
|
|
261
|
+
svg.renderToCanvas(Canvas(bitmap))
|
|
262
|
+
return bitmap
|
|
263
|
+
}
|
|
264
|
+
}
|