@c9up/orbit 0.0.0-stage → 0.1.0
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/Cargo.lock +146 -0
- package/Cargo.toml +16 -0
- package/LICENSE +21 -0
- package/README.md +314 -2
- package/android/orbit.cmake +31 -0
- package/android/src/main/cpp/NativeOrbit.cpp +309 -0
- package/android/src/main/cpp/NativeOrbit.h +35 -0
- package/android/src/main/cpp/orbit_host.h +34 -0
- package/android/src/main/java/com/c9up/orbit/OrbitEffects.kt +286 -0
- package/android/src/main/java/com/c9up/orbit/OrbitHost.kt +258 -0
- package/android/src/main/java/com/c9up/orbit/OrbitImage.kt +346 -0
- package/android/src/main/java/com/c9up/orbit/OrbitInput.kt +145 -0
- package/android/src/main/java/com/c9up/orbit/OrbitPress.kt +110 -0
- package/android/src/main/java/com/c9up/orbit/OrbitVector.kt +115 -0
- package/android/src/main/java/com/c9up/orbit/OrbitViews.kt +362 -0
- package/crates/orbit-host/Cargo.toml +14 -0
- package/crates/orbit-host/src/gesture.rs +561 -0
- package/crates/orbit-host/src/lib.rs +1608 -0
- package/crates/orbit-host/src/motion.rs +328 -0
- package/crates/orbit-host/src/vector.rs +917 -0
- package/dist/color.d.ts +10 -0
- package/dist/color.d.ts.map +1 -0
- package/dist/color.js +62 -0
- package/dist/color.js.map +1 -0
- package/dist/commit.d.ts +45 -0
- package/dist/commit.d.ts.map +1 -0
- package/dist/commit.js +172 -0
- package/dist/commit.js.map +1 -0
- package/dist/errors.d.ts +42 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -0
- package/dist/host.d.ts +49 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +18 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +29 -0
- package/dist/index.js.map +1 -0
- package/dist/motion.d.ts +18 -0
- package/dist/motion.d.ts.map +1 -0
- package/dist/motion.js +66 -0
- package/dist/motion.js.map +1 -0
- package/dist/node.d.ts +46 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +110 -0
- package/dist/node.js.map +1 -0
- package/dist/pages.d.ts +56 -0
- package/dist/pages.d.ts.map +1 -0
- package/dist/pages.js +157 -0
- package/dist/pages.js.map +1 -0
- package/dist/react-native/index.d.ts +25 -0
- package/dist/react-native/index.d.ts.map +1 -0
- package/dist/react-native/index.js +43 -0
- package/dist/react-native/index.js.map +1 -0
- package/dist/server.d.ts +85 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +282 -0
- package/dist/server.js.map +1 -0
- package/dist/stack.d.ts +117 -0
- package/dist/stack.d.ts.map +1 -0
- package/dist/stack.js +299 -0
- package/dist/stack.js.map +1 -0
- package/dist/styles.d.ts +138 -0
- package/dist/styles.d.ts.map +1 -0
- package/dist/styles.js +920 -0
- package/dist/styles.js.map +1 -0
- package/dist/template.d.ts +27 -0
- package/dist/template.d.ts.map +1 -0
- package/dist/template.js +1392 -0
- package/dist/template.js.map +1 -0
- package/dist/url.d.ts +45 -0
- package/dist/url.d.ts.map +1 -0
- package/dist/url.js +302 -0
- package/dist/url.js.map +1 -0
- package/package.json +90 -3
- package/scripts/build-android.sh +27 -0
- package/scripts/test-styles.mjs +31 -0
- package/specs/NativeOrbit.ts +34 -0
- package/src/color.ts +73 -0
- package/src/commit.ts +206 -0
- package/src/errors.ts +48 -0
- package/src/host.ts +92 -0
- package/src/index.ts +60 -0
- package/src/motion.ts +86 -0
- package/src/node.ts +133 -0
- package/src/pages.ts +210 -0
- package/src/react-native/index.ts +76 -0
- package/src/react-native/react-native.d.ts +31 -0
- package/src/server.ts +359 -0
- package/src/stack.ts +434 -0
- package/src/styles.ts +1024 -0
- package/src/template.ts +1657 -0
- package/src/url.ts +326 -0
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
package com.c9up.orbit
|
|
2
|
+
|
|
3
|
+
import android.app.Activity
|
|
4
|
+
import android.os.Handler
|
|
5
|
+
import android.os.Looper
|
|
6
|
+
import android.view.Choreographer
|
|
7
|
+
import android.view.View
|
|
8
|
+
import android.view.ViewGroup
|
|
9
|
+
import java.nio.ByteBuffer
|
|
10
|
+
import java.nio.ByteOrder
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The platform side of orbit's Rust host. orbit-host (Rust) owns the
|
|
14
|
+
* tree, the layout and the diff; this object only applies its mount operations
|
|
15
|
+
* to real Android views on the UI thread, measures text for its layout, and
|
|
16
|
+
* hands touches back to JS. Op codes match rust/orbit-host/src/lib.rs.
|
|
17
|
+
*/
|
|
18
|
+
object OrbitHost {
|
|
19
|
+
private const val OP_CREATE = 1
|
|
20
|
+
private const val OP_DELETE = 2
|
|
21
|
+
private const val OP_CHILDREN = 3
|
|
22
|
+
private const val OP_FRAME = 4
|
|
23
|
+
private const val OP_VIEW_STYLE = 5
|
|
24
|
+
private const val OP_TEXT = 6
|
|
25
|
+
private const val OP_ROOT = 7
|
|
26
|
+
private const val OP_INPUT = 8
|
|
27
|
+
private const val OP_IMAGE = 9
|
|
28
|
+
private const val OP_VECTOR = 11
|
|
29
|
+
private const val OP_EFFECTS = 10
|
|
30
|
+
|
|
31
|
+
@JvmStatic external fun nativeInit()
|
|
32
|
+
|
|
33
|
+
@JvmStatic external fun nativeDispatch(tag: Int, type: String, x: Float, y: Float)
|
|
34
|
+
|
|
35
|
+
@JvmStatic external fun nativeDispatchText(tag: Int, type: String, text: String)
|
|
36
|
+
|
|
37
|
+
@JvmStatic external fun nativeViewport(width: Float, height: Float)
|
|
38
|
+
|
|
39
|
+
/** A touch for orbit-host's gesture recognizer (action 0 down, 1 move, 2 up, 3 cancel; dp). */
|
|
40
|
+
@JvmStatic external fun nativeTouch(action: Int, x: Float, y: Float, nowNs: Long, hit: Int): ByteArray
|
|
41
|
+
|
|
42
|
+
@JvmStatic external fun nativeGestureTick(nowNs: Long): ByteArray
|
|
43
|
+
|
|
44
|
+
fun viewOf(tag: Int): View? = views[tag]
|
|
45
|
+
|
|
46
|
+
/** The safe area changed (bars, cutout, keyboard): JS lays out again, now or once it listens. */
|
|
47
|
+
fun reportViewport(width: Float, height: Float) = nativeViewport(width, height)
|
|
48
|
+
|
|
49
|
+
@JvmStatic external fun nativeTick(nowNs: Long, scrollTags: IntArray, scrollY: FloatArray): ByteArray
|
|
50
|
+
|
|
51
|
+
private const val PROP_OPACITY = 0
|
|
52
|
+
private const val PROP_TRANSLATE_X = 1
|
|
53
|
+
private const val PROP_TRANSLATE_Y = 2
|
|
54
|
+
private const val PROP_SCALE = 3
|
|
55
|
+
private const val PROP_VISIBLE = 4
|
|
56
|
+
|
|
57
|
+
/** Every vsync: orbit-host advances its animations; no JS involved. */
|
|
58
|
+
private val frame = object : Choreographer.FrameCallback {
|
|
59
|
+
override fun doFrame(frameTimeNanos: Long) {
|
|
60
|
+
val scrolls = views.values.filterIsInstance<OrbitScroll>()
|
|
61
|
+
val tags = IntArray(scrolls.size) { scrolls[it].tag as Int }
|
|
62
|
+
val ys = FloatArray(scrolls.size) { scrolls[it].scrollY / density }
|
|
63
|
+
root?.let { OrbitPress.apply(it, nativeGestureTick(frameTimeNanos)) }
|
|
64
|
+
val out = nativeTick(frameTimeNanos, tags, ys)
|
|
65
|
+
val buf = ByteBuffer.wrap(out, 1, out.size - 1).order(ByteOrder.LITTLE_ENDIAN)
|
|
66
|
+
if (buf.remaining() >= 9) OrbitEffects.invalidateBackdrops()
|
|
67
|
+
while (buf.remaining() >= 9) {
|
|
68
|
+
val tag = buf.int
|
|
69
|
+
val prop = buf.get().toInt()
|
|
70
|
+
val value = buf.float
|
|
71
|
+
val view = views[tag]
|
|
72
|
+
if (view == null) {
|
|
73
|
+
// Bound right after a commit whose views are not mounted yet: the
|
|
74
|
+
// host sends a value once, so keep it for the view's creation.
|
|
75
|
+
early.getOrPut(tag) { HashMap() }[prop] = value
|
|
76
|
+
continue
|
|
77
|
+
}
|
|
78
|
+
applyMotion(view, prop, value)
|
|
79
|
+
}
|
|
80
|
+
Choreographer.getInstance().postFrameCallback(this)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Motion values that reached a view before its creation, by tag then prop. */
|
|
85
|
+
private val early = HashMap<Int, HashMap<Int, Float>>()
|
|
86
|
+
|
|
87
|
+
private fun applyMotion(view: View, prop: Int, value: Float) {
|
|
88
|
+
when (prop) {
|
|
89
|
+
PROP_OPACITY -> view.alpha = value
|
|
90
|
+
PROP_TRANSLATE_X -> view.translationX = value * density
|
|
91
|
+
PROP_TRANSLATE_Y -> view.translationY = value * density
|
|
92
|
+
PROP_SCALE -> { view.scaleX = value; view.scaleY = value }
|
|
93
|
+
// Invisible keeps the layout (and a scroll view's offset) but is not
|
|
94
|
+
// drawn and takes no touch: a covered screen.
|
|
95
|
+
PROP_VISIBLE -> view.visibility = if (value > 0.5f) View.VISIBLE else View.INVISIBLE
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private val main = Handler(Looper.getMainLooper())
|
|
100
|
+
private val views = HashMap<Int, View>()
|
|
101
|
+
private var root: OrbitRoot? = null
|
|
102
|
+
var density = 1f
|
|
103
|
+
private set
|
|
104
|
+
|
|
105
|
+
/** `animate`: tick animations into views on vsync (view host); the self-drawn host ticks them while drawing. */
|
|
106
|
+
fun attach(activity: Activity, animate: Boolean = true): View {
|
|
107
|
+
density = activity.resources.displayMetrics.density
|
|
108
|
+
// The C++ side lives in libappmodules; make sure it is loaded before binding.
|
|
109
|
+
com.facebook.soloader.SoLoader.loadLibrary("appmodules")
|
|
110
|
+
nativeInit()
|
|
111
|
+
val view = OrbitRoot(activity)
|
|
112
|
+
root = view
|
|
113
|
+
if (animate) Choreographer.getInstance().postFrameCallback(frame)
|
|
114
|
+
return view
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Called by the C++ module on the JS thread; applied on the UI thread. */
|
|
118
|
+
@JvmStatic
|
|
119
|
+
fun apply(ops: ByteArray) {
|
|
120
|
+
main.post {
|
|
121
|
+
applyNow(ops)
|
|
122
|
+
OrbitEffects.invalidateBackdrops()
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Called by the C++ module on the JS thread: scroll a scroll view by `by` dp, or to its end. */
|
|
127
|
+
@JvmStatic
|
|
128
|
+
fun scroll(tag: Int, by: Float, toEnd: Boolean) {
|
|
129
|
+
main.post {
|
|
130
|
+
val view = views[tag] as? OrbitScroll ?: return@post
|
|
131
|
+
if (toEnd) {
|
|
132
|
+
val content = view.getChildAt(0)
|
|
133
|
+
view.scrollTo(0, maxOf(0, (content?.bottom ?: 0) - view.height))
|
|
134
|
+
} else {
|
|
135
|
+
view.scrollBy(0, (by * density).toInt())
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Called by the C++ module on the JS thread: an image node's bytes, kept in memory. */
|
|
141
|
+
@JvmStatic
|
|
142
|
+
fun imageBytes(tag: Int, bytes: ByteArray) = OrbitImages.put(tag, bytes)
|
|
143
|
+
|
|
144
|
+
/** Text size in dp, packed as two float bit patterns (width high, height low). */
|
|
145
|
+
@JvmStatic
|
|
146
|
+
fun measureText(spans: ByteArray, maxWidth: Float): Long {
|
|
147
|
+
val text = OrbitText.decode(spans, density)
|
|
148
|
+
val maxPx = if (maxWidth.isInfinite() || maxWidth > 1e6f) Int.MAX_VALUE / 2 else (maxWidth * density).toInt()
|
|
149
|
+
val (w, h) = text.measure(maxPx)
|
|
150
|
+
// The width in whole dp, rounded up: the layout rounds frames to whole dp,
|
|
151
|
+
// and a text even a fraction narrower than it measured wraps and loses its
|
|
152
|
+
// last word. The height stays exact — rounded up, every line of a
|
|
153
|
+
// 19.25 dp line height grew by most of a dp against the web.
|
|
154
|
+
val wBits = java.lang.Float.floatToRawIntBits(kotlin.math.ceil(w / density)).toLong()
|
|
155
|
+
val hBits = java.lang.Float.floatToRawIntBits(h / density).toLong()
|
|
156
|
+
return (wBits shl 32) or (hBits and 0xffffffffL)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
private fun applyNow(ops: ByteArray) {
|
|
160
|
+
val root = root ?: return
|
|
161
|
+
val buf = ByteBuffer.wrap(ops).order(ByteOrder.LITTLE_ENDIAN)
|
|
162
|
+
val context = root.context
|
|
163
|
+
while (buf.hasRemaining()) {
|
|
164
|
+
val code = buf.get().toInt()
|
|
165
|
+
val tag = buf.int
|
|
166
|
+
when (code) {
|
|
167
|
+
OP_CREATE -> {
|
|
168
|
+
val view: View = when (buf.get().toInt()) {
|
|
169
|
+
1 -> OrbitTextView(context)
|
|
170
|
+
2 -> OrbitScroll(context)
|
|
171
|
+
3 -> OrbitInput(context)
|
|
172
|
+
4 -> OrbitImage(context)
|
|
173
|
+
5 -> OrbitVector(context)
|
|
174
|
+
else -> OrbitBox(context)
|
|
175
|
+
}
|
|
176
|
+
view.tag = tag
|
|
177
|
+
views[tag] = view
|
|
178
|
+
early.remove(tag)?.forEach { (prop, value) -> applyMotion(view, prop, value) }
|
|
179
|
+
}
|
|
180
|
+
OP_DELETE -> {
|
|
181
|
+
early.remove(tag)
|
|
182
|
+
views.remove(tag)?.let { (it.parent as? ViewGroup)?.removeView(it) }
|
|
183
|
+
OrbitImages.release(tag)
|
|
184
|
+
}
|
|
185
|
+
OP_CHILDREN -> {
|
|
186
|
+
val parent = views[tag] as? ViewGroup
|
|
187
|
+
val count = buf.int
|
|
188
|
+
val wanted = ArrayList<View>(count)
|
|
189
|
+
repeat(count) { views[buf.int]?.let(wanted::add) }
|
|
190
|
+
if (parent != null) setChildren(parent, wanted)
|
|
191
|
+
}
|
|
192
|
+
OP_FRAME -> {
|
|
193
|
+
val x = buf.float; val y = buf.float; val w = buf.float; val h = buf.float
|
|
194
|
+
(views[tag] as? Framed)?.setFrame(x * density, y * density, w * density, h * density)
|
|
195
|
+
}
|
|
196
|
+
OP_VIEW_STYLE -> {
|
|
197
|
+
val background = buf.int; val borderColor = buf.int
|
|
198
|
+
val borderWidth = buf.float; val radius = buf.float; val opacity = buf.float
|
|
199
|
+
(views[tag] as? Framed)?.setLook(background, borderColor, borderWidth * density, radius * density, opacity)
|
|
200
|
+
}
|
|
201
|
+
OP_TEXT -> {
|
|
202
|
+
val bytes = ByteArray(buf.int)
|
|
203
|
+
buf.get(bytes)
|
|
204
|
+
(views[tag] as? OrbitTextView)?.setText(OrbitText.decode(bytes, density))
|
|
205
|
+
}
|
|
206
|
+
OP_INPUT -> {
|
|
207
|
+
val bytes = ByteArray(buf.int)
|
|
208
|
+
buf.get(bytes)
|
|
209
|
+
(views[tag] as? OrbitInput)?.apply(String(bytes, Charsets.UTF_8), density)
|
|
210
|
+
}
|
|
211
|
+
OP_IMAGE -> {
|
|
212
|
+
val bytes = ByteArray(buf.int)
|
|
213
|
+
buf.get(bytes)
|
|
214
|
+
(views[tag] as? OrbitImage)?.apply(String(bytes, Charsets.UTF_8))
|
|
215
|
+
}
|
|
216
|
+
OP_VECTOR -> {
|
|
217
|
+
val bytes = ByteArray(buf.int)
|
|
218
|
+
buf.get(bytes)
|
|
219
|
+
(views[tag] as? OrbitVector)?.apply(bytes)
|
|
220
|
+
}
|
|
221
|
+
OP_EFFECTS -> {
|
|
222
|
+
val dx = buf.float; val dy = buf.float; val blur = buf.float; val spread = buf.float
|
|
223
|
+
val color = buf.int; val backdrop = buf.float; val clip = buf.get().toInt() != 0
|
|
224
|
+
views[tag]?.let { view ->
|
|
225
|
+
val shadow = if (color ushr 24 == 0) null else Shadow(dx * density, dy * density, blur * density, spread * density, color)
|
|
226
|
+
OrbitEffects.apply(view, shadow, backdrop * density, clip)
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
OP_ROOT -> views[tag]?.let { setChildren(root.content, listOf(it)) }
|
|
230
|
+
else -> throw IllegalStateException("unknown op $code")
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Make `parent`'s children exactly `wanted`, moving only what is out of place. */
|
|
236
|
+
private fun setChildren(parent: ViewGroup, wanted: List<View>) {
|
|
237
|
+
for ((i, child) in wanted.withIndex()) {
|
|
238
|
+
if (parent.getChildAt(i) === child) continue
|
|
239
|
+
(child.parent as? ViewGroup)?.removeView(child)
|
|
240
|
+
parent.addView(child, i)
|
|
241
|
+
}
|
|
242
|
+
while (parent.childCount > wanted.size) parent.removeViewAt(parent.childCount - 1)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** The deepest host view under (x, y) in root pixels, as a tag. */
|
|
246
|
+
fun hitTest(group: ViewGroup, x: Float, y: Float): Int? {
|
|
247
|
+
for (i in group.childCount - 1 downTo 0) {
|
|
248
|
+
val child = group.getChildAt(i)
|
|
249
|
+
val left = child.left + child.translationX
|
|
250
|
+
val top = child.top + child.translationY
|
|
251
|
+
if (child.visibility == View.VISIBLE && x >= left && x < left + child.width && y >= top && y < top + child.height) {
|
|
252
|
+
val inner = (child as? ViewGroup)?.let { hitTest(it, x - left + child.scrollX, y - top + child.scrollY) }
|
|
253
|
+
return inner ?: (child.tag as? Int)
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return null
|
|
257
|
+
}
|
|
258
|
+
}
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
package com.c9up.orbit
|
|
2
|
+
|
|
3
|
+
import android.content.Context
|
|
4
|
+
import android.graphics.Bitmap
|
|
5
|
+
import android.graphics.BitmapFactory
|
|
6
|
+
import android.graphics.Canvas
|
|
7
|
+
import android.graphics.ImageDecoder
|
|
8
|
+
import android.graphics.Matrix
|
|
9
|
+
import android.graphics.Outline
|
|
10
|
+
import android.graphics.Paint
|
|
11
|
+
import android.graphics.drawable.GradientDrawable
|
|
12
|
+
import android.net.Uri
|
|
13
|
+
import android.os.Build
|
|
14
|
+
import android.os.Handler
|
|
15
|
+
import android.os.Looper
|
|
16
|
+
import android.os.Process
|
|
17
|
+
import android.util.LruCache
|
|
18
|
+
import android.view.View
|
|
19
|
+
import android.view.ViewOutlineProvider
|
|
20
|
+
import org.json.JSONObject
|
|
21
|
+
import java.io.ByteArrayOutputStream
|
|
22
|
+
import java.io.File
|
|
23
|
+
import java.io.IOException
|
|
24
|
+
import java.io.InputStream
|
|
25
|
+
import java.net.URL
|
|
26
|
+
import java.nio.ByteBuffer
|
|
27
|
+
import java.util.concurrent.Executors
|
|
28
|
+
import javax.net.ssl.HttpsURLConnection
|
|
29
|
+
import kotlin.math.ceil
|
|
30
|
+
import kotlin.math.max
|
|
31
|
+
import kotlin.math.min
|
|
32
|
+
import kotlin.math.roundToInt
|
|
33
|
+
|
|
34
|
+
/** A decoded image and the size its source declared. */
|
|
35
|
+
class Decoded(val bitmap: Bitmap, val naturalWidth: Int, val naturalHeight: Int)
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Where images come from, decoded off the UI thread at the size their view
|
|
39
|
+
* shows them, and a bounded cache of what is decoded.
|
|
40
|
+
*
|
|
41
|
+
* Sources, as orbit's template writes them: `https://…`, `file:<path>`,
|
|
42
|
+
* `content://…`, `asset:<name>` (bundled with the app) and `bytes:<n>` — the
|
|
43
|
+
* bytes JS handed over for that node (`imageBytes`), held in memory only,
|
|
44
|
+
* never written to disk, and zeroed when the node goes.
|
|
45
|
+
*/
|
|
46
|
+
object OrbitImages {
|
|
47
|
+
/** A download or a local file larger than this is refused, not read. */
|
|
48
|
+
private const val MAX_SOURCE_BYTES = 64 * 1024 * 1024
|
|
49
|
+
/** No decoded side exceeds this, whatever the source declares. */
|
|
50
|
+
private const val MAX_SIDE = 4096
|
|
51
|
+
private const val TIMEOUT_MS = 15_000
|
|
52
|
+
|
|
53
|
+
private val main = Handler(Looper.getMainLooper())
|
|
54
|
+
private val workers = Executors.newFixedThreadPool(3) { task ->
|
|
55
|
+
Thread({
|
|
56
|
+
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)
|
|
57
|
+
task.run()
|
|
58
|
+
}, "orbit-image").apply { isDaemon = true }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Bounded by decoded pixels: an eighth of what the app may allocate.
|
|
62
|
+
private val cache = object : LruCache<String, Decoded>((Runtime.getRuntime().maxMemory() / 8 / 1024).toInt()) {
|
|
63
|
+
override fun sizeOf(key: String, value: Decoded) = value.bitmap.allocationByteCount / 1024
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** UI thread only: the loads in flight, so one decode serves every view that waits for it. */
|
|
67
|
+
private val pending = HashMap<String, MutableList<(Decoded?) -> Unit>>()
|
|
68
|
+
|
|
69
|
+
private val bytes = HashMap<Int, ByteArray>()
|
|
70
|
+
|
|
71
|
+
/** JS thread: the bytes a node shows from now on. */
|
|
72
|
+
fun put(tag: Int, data: ByteArray) {
|
|
73
|
+
val previous = synchronized(bytes) { bytes.put(tag, data) }
|
|
74
|
+
previous?.fill(0)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** UI thread: the node is gone — its bytes are zeroed, its decoded pixels evicted. */
|
|
78
|
+
fun release(tag: Int) {
|
|
79
|
+
val held = synchronized(bytes) { bytes.remove(tag) } ?: return
|
|
80
|
+
held.fill(0)
|
|
81
|
+
val prefix = "bytes:$tag:"
|
|
82
|
+
for (key in cache.snapshot().keys) if (key.startsWith(prefix)) cache.remove(key)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* UI thread: `done` gets the image decoded for a `width` x `height` px view
|
|
87
|
+
* under `fit`, on the UI thread, or null when it could not be loaded.
|
|
88
|
+
*/
|
|
89
|
+
fun load(context: Context, src: String, tag: Int, width: Int, height: Int, fit: String, done: (Decoded?) -> Unit) {
|
|
90
|
+
val source = if (src.startsWith("bytes:")) "bytes:$tag:${src.substring(6)}" else src
|
|
91
|
+
val key = "$source@${width}x$height/$fit"
|
|
92
|
+
cache.get(key)?.let { return done(it) }
|
|
93
|
+
pending[key]?.let { it.add(done); return }
|
|
94
|
+
pending[key] = mutableListOf(done)
|
|
95
|
+
val app = context.applicationContext
|
|
96
|
+
workers.execute {
|
|
97
|
+
val decoded = try {
|
|
98
|
+
decode(app, src, tag, width, height, fit)
|
|
99
|
+
} catch (e: Exception) {
|
|
100
|
+
android.util.Log.w("ORBIT", "image $src: ${e.message}")
|
|
101
|
+
null
|
|
102
|
+
} catch (e: OutOfMemoryError) {
|
|
103
|
+
android.util.Log.w("ORBIT", "image $src: out of memory")
|
|
104
|
+
null
|
|
105
|
+
}
|
|
106
|
+
main.post {
|
|
107
|
+
if (decoded != null) cache.put(key, decoded)
|
|
108
|
+
pending.remove(key)?.forEach { it(decoded) }
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The decoded size for a view: enough pixels for what the fit shows, never
|
|
115
|
+
* more than the source has nor than MAX_SIDE — so what is allocated follows
|
|
116
|
+
* the view, not the size a (possibly hostile) header claims.
|
|
117
|
+
*/
|
|
118
|
+
private fun target(naturalW: Int, naturalH: Int, width: Int, height: Int, fit: String): Pair<Int, Int> {
|
|
119
|
+
val w = max(naturalW, 1).toFloat()
|
|
120
|
+
val h = max(naturalH, 1).toFloat()
|
|
121
|
+
val x = max(width, 1) / w
|
|
122
|
+
val y = max(height, 1) / h
|
|
123
|
+
var scale = when (fit) {
|
|
124
|
+
"cover" -> max(x, y)
|
|
125
|
+
"none" -> 1f
|
|
126
|
+
"fill" -> max(x, y)
|
|
127
|
+
else -> min(x, y)
|
|
128
|
+
}
|
|
129
|
+
scale = min(scale, 1f)
|
|
130
|
+
scale = min(scale, MAX_SIDE / max(w, h))
|
|
131
|
+
return Pair(max((w * scale).roundToInt(), 1), max((h * scale).roundToInt(), 1))
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
private fun decode(context: Context, src: String, tag: Int, width: Int, height: Int, fit: String): Decoded? {
|
|
135
|
+
var held: ByteArray? = null
|
|
136
|
+
try {
|
|
137
|
+
if (src.startsWith("bytes:")) {
|
|
138
|
+
// A copy: the node may go (and its bytes be zeroed) while this decodes.
|
|
139
|
+
held = synchronized(bytes) { bytes[tag]?.copyOf() } ?: return null
|
|
140
|
+
} else if (src.startsWith("https://")) {
|
|
141
|
+
held = download(src)
|
|
142
|
+
}
|
|
143
|
+
if (Build.VERSION.SDK_INT >= 28) {
|
|
144
|
+
val source = when {
|
|
145
|
+
held != null -> ImageDecoder.createSource(ByteBuffer.wrap(held))
|
|
146
|
+
src.startsWith("file:") -> ImageDecoder.createSource(File(src.substring(5)))
|
|
147
|
+
src.startsWith("content://") -> ImageDecoder.createSource(context.contentResolver, Uri.parse(src))
|
|
148
|
+
src.startsWith("asset:") -> ImageDecoder.createSource(context.assets, src.substring(6))
|
|
149
|
+
else -> return null
|
|
150
|
+
}
|
|
151
|
+
var naturalW = 0
|
|
152
|
+
var naturalH = 0
|
|
153
|
+
val bitmap = ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
|
|
154
|
+
naturalW = info.size.width
|
|
155
|
+
naturalH = info.size.height
|
|
156
|
+
val (w, h) = target(naturalW, naturalH, width, height, fit)
|
|
157
|
+
decoder.setTargetSize(w, h)
|
|
158
|
+
// Software: the view may be drawn into a software canvas (snapshots, blur).
|
|
159
|
+
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
|
|
160
|
+
}
|
|
161
|
+
return Decoded(bitmap, naturalW, naturalH)
|
|
162
|
+
}
|
|
163
|
+
val data = held ?: when {
|
|
164
|
+
src.startsWith("file:") -> File(src.substring(5)).inputStream().use(::readCapped)
|
|
165
|
+
src.startsWith("content://") ->
|
|
166
|
+
context.contentResolver.openInputStream(Uri.parse(src))?.use(::readCapped) ?: return null
|
|
167
|
+
src.startsWith("asset:") -> context.assets.open(src.substring(6)).use(::readCapped)
|
|
168
|
+
else -> return null
|
|
169
|
+
}
|
|
170
|
+
return decodeLegacy(data, width, height, fit)
|
|
171
|
+
} finally {
|
|
172
|
+
held?.fill(0)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Before Android 9: BitmapFactory, sampled down by powers of two (no EXIF rotation). */
|
|
177
|
+
private fun decodeLegacy(data: ByteArray, width: Int, height: Int, fit: String): Decoded? {
|
|
178
|
+
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
|
179
|
+
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
|
|
180
|
+
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
|
|
181
|
+
val (w, h) = target(bounds.outWidth, bounds.outHeight, width, height, fit)
|
|
182
|
+
var sample = 1
|
|
183
|
+
while (bounds.outWidth / (sample * 2) >= w && bounds.outHeight / (sample * 2) >= h) sample *= 2
|
|
184
|
+
// Never above MAX_SIDE, even when the fit wanted every pixel.
|
|
185
|
+
while (max(bounds.outWidth, bounds.outHeight) / sample > MAX_SIDE) sample *= 2
|
|
186
|
+
val options = BitmapFactory.Options().apply { inSampleSize = sample }
|
|
187
|
+
val bitmap = BitmapFactory.decodeByteArray(data, 0, data.size, options) ?: return null
|
|
188
|
+
return Decoded(bitmap, bounds.outWidth, bounds.outHeight)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** https only (the connection is refused otherwise), size-capped, with timeouts. */
|
|
192
|
+
private fun download(url: String): ByteArray {
|
|
193
|
+
val connection = URL(url).openConnection() as? HttpsURLConnection
|
|
194
|
+
?: throw IOException("not an https URL")
|
|
195
|
+
try {
|
|
196
|
+
connection.connectTimeout = TIMEOUT_MS
|
|
197
|
+
connection.readTimeout = TIMEOUT_MS
|
|
198
|
+
// HttpURLConnection never follows a redirect from https to http.
|
|
199
|
+
connection.instanceFollowRedirects = true
|
|
200
|
+
val status = connection.responseCode
|
|
201
|
+
if (status !in 200..299) throw IOException("HTTP $status")
|
|
202
|
+
if (connection.contentLengthLong > MAX_SOURCE_BYTES) throw IOException("larger than $MAX_SOURCE_BYTES bytes")
|
|
203
|
+
return connection.inputStream.use(::readCapped)
|
|
204
|
+
} finally {
|
|
205
|
+
connection.disconnect()
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
private fun readCapped(input: InputStream): ByteArray {
|
|
210
|
+
val out = ByteArrayOutputStream()
|
|
211
|
+
val chunk = ByteArray(64 * 1024)
|
|
212
|
+
while (true) {
|
|
213
|
+
val n = input.read(chunk)
|
|
214
|
+
if (n < 0) break
|
|
215
|
+
if (out.size() + n > MAX_SOURCE_BYTES) throw IOException("larger than $MAX_SOURCE_BYTES bytes")
|
|
216
|
+
out.write(chunk, 0, n)
|
|
217
|
+
}
|
|
218
|
+
return out.toByteArray()
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* `<img>`: draws the image orbit-host placed, fitted as CSS object-fit does
|
|
224
|
+
* (`fill` by default), clipped to its rounded corners, with its border on top.
|
|
225
|
+
*/
|
|
226
|
+
class OrbitImage(context: Context) : View(context), Framed {
|
|
227
|
+
val frame = FloatArray(4)
|
|
228
|
+
private var src = ""
|
|
229
|
+
private var fit = "fill"
|
|
230
|
+
private var decoded: Decoded? = null
|
|
231
|
+
/** The view size the current image was decoded for, in px. */
|
|
232
|
+
private var decodedFor = Pair(0, 0)
|
|
233
|
+
private var request = 0
|
|
234
|
+
private var radius = 0f
|
|
235
|
+
private var borderWidth = 0f
|
|
236
|
+
private val paint = Paint(Paint.FILTER_BITMAP_FLAG or Paint.ANTI_ALIAS_FLAG)
|
|
237
|
+
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
|
|
238
|
+
private val drawMatrix = Matrix()
|
|
239
|
+
|
|
240
|
+
init {
|
|
241
|
+
outlineProvider = object : ViewOutlineProvider() {
|
|
242
|
+
override fun getOutline(view: View, outline: Outline) {
|
|
243
|
+
val r = min(radius, min(view.width, view.height) / 2f)
|
|
244
|
+
outline.setRoundRect(0, 0, view.width, view.height, r)
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** The image op's payload: `{src, fit, alt}`. */
|
|
250
|
+
fun apply(json: String) {
|
|
251
|
+
val props = JSONObject(json)
|
|
252
|
+
val nextSrc = props.optString("src")
|
|
253
|
+
val nextFit = props.optString("fit", "fill")
|
|
254
|
+
val alt = props.optString("alt")
|
|
255
|
+
contentDescription = alt.ifEmpty { null }
|
|
256
|
+
importantForAccessibility =
|
|
257
|
+
if (alt.isEmpty()) IMPORTANT_FOR_ACCESSIBILITY_NO else IMPORTANT_FOR_ACCESSIBILITY_YES
|
|
258
|
+
val changed = nextSrc != src || nextFit != fit
|
|
259
|
+
src = nextSrc
|
|
260
|
+
fit = nextFit
|
|
261
|
+
if (changed) {
|
|
262
|
+
decoded = null
|
|
263
|
+
decodedFor = Pair(0, 0)
|
|
264
|
+
load()
|
|
265
|
+
}
|
|
266
|
+
invalidate()
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
override fun setFrame(x: Float, y: Float, w: Float, h: Float) {
|
|
270
|
+
frame[0] = x; frame[1] = y; frame[2] = w; frame[3] = h
|
|
271
|
+
applyFrame(frame)
|
|
272
|
+
invalidateOutline()
|
|
273
|
+
// Grown past what was decoded: decode again, sharper. Shrinking keeps it.
|
|
274
|
+
val (dw, dh) = decodedFor
|
|
275
|
+
if (ceil(w).toInt() > dw || ceil(h).toInt() > dh) load()
|
|
276
|
+
invalidate()
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
override fun setLook(background: Int, borderColor: Int, borderWidth: Float, radius: Float, opacity: Float) {
|
|
280
|
+
OrbitEffects.setRadius(this, radius)
|
|
281
|
+
this.radius = radius
|
|
282
|
+
this.borderWidth = borderWidth
|
|
283
|
+
stroke.color = borderColor
|
|
284
|
+
stroke.strokeWidth = borderWidth
|
|
285
|
+
this.background = if (background == 0) null else GradientDrawable().apply {
|
|
286
|
+
setColor(background)
|
|
287
|
+
cornerRadius = radius
|
|
288
|
+
}
|
|
289
|
+
clipToOutline = radius > 0f
|
|
290
|
+
invalidateOutline()
|
|
291
|
+
alpha = opacity
|
|
292
|
+
invalidate()
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
|
296
|
+
setMeasuredDimension(frame[2].toInt(), frame[3].toInt())
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
private fun load() {
|
|
300
|
+
val tag = tag as? Int ?: return
|
|
301
|
+
val w = ceil(frame[2]).toInt()
|
|
302
|
+
val h = ceil(frame[3]).toInt()
|
|
303
|
+
if (src.isEmpty() || w <= 0 || h <= 0) return
|
|
304
|
+
val token = ++request
|
|
305
|
+
decodedFor = Pair(w, h)
|
|
306
|
+
OrbitImages.load(context, src, tag, w, h, fit) { image ->
|
|
307
|
+
if (token != request) return@load
|
|
308
|
+
decoded = image
|
|
309
|
+
invalidate()
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
override fun onDraw(canvas: Canvas) {
|
|
314
|
+
val w = width.toFloat()
|
|
315
|
+
val h = height.toFloat()
|
|
316
|
+
decoded?.let { image ->
|
|
317
|
+
val bw = image.bitmap.width.toFloat()
|
|
318
|
+
val bh = image.bitmap.height.toFloat()
|
|
319
|
+
// `none` shows the natural size: one image pixel per dp, as one per CSS px.
|
|
320
|
+
val natural = OrbitHost.density * image.naturalWidth / bw
|
|
321
|
+
drawMatrix.reset()
|
|
322
|
+
if (fit == "fill") {
|
|
323
|
+
drawMatrix.setScale(w / bw, h / bh)
|
|
324
|
+
} else {
|
|
325
|
+
val contain = min(w / bw, h / bh)
|
|
326
|
+
val scale = when (fit) {
|
|
327
|
+
"cover" -> max(w / bw, h / bh)
|
|
328
|
+
"none" -> natural
|
|
329
|
+
"scale-down" -> min(contain, natural)
|
|
330
|
+
else -> contain
|
|
331
|
+
}
|
|
332
|
+
drawMatrix.setScale(scale, scale)
|
|
333
|
+
drawMatrix.postTranslate((w - bw * scale) / 2f, (h - bh * scale) / 2f)
|
|
334
|
+
}
|
|
335
|
+
canvas.save()
|
|
336
|
+
canvas.clipRect(0f, 0f, w, h)
|
|
337
|
+
canvas.drawBitmap(image.bitmap, drawMatrix, paint)
|
|
338
|
+
canvas.restore()
|
|
339
|
+
}
|
|
340
|
+
if (borderWidth > 0f) {
|
|
341
|
+
val inset = borderWidth / 2f
|
|
342
|
+
val r = max(min(radius, min(w, h) / 2f) - inset, 0f)
|
|
343
|
+
canvas.drawRoundRect(inset, inset, w - inset, h - inset, r, r, stroke)
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|