@nativue/core 0.5.0 → 0.6.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.
@@ -46,6 +46,19 @@ struct Runtime {
46
46
  jobject owner;
47
47
  };
48
48
 
49
+ // Calls the Kotlin native function at `index` with one string, outside any JS call: no JS value to
50
+ // return, no JS error to throw.
51
+ void callNativeWithString(jobject owner, jint index, const std::string& argument) {
52
+ JNIEnv* env = currentEnvironment();
53
+ if (env == nullptr) return;
54
+
55
+ env->PushLocalFrame(4);
56
+ jobjectArray arguments = env->NewObjectArray(1, types.object, env->NewStringUTF(argument.c_str()));
57
+ env->CallObjectMethod(owner, types.callNative, index, arguments);
58
+ if (env->ExceptionCheck()) env->ExceptionClear();
59
+ env->PopLocalFrame(nullptr);
60
+ }
61
+
49
62
  // ---------- Strings (UTF-16 both ways, so emoji survive) ----------
50
63
 
51
64
  jstring toJavaString(JNIEnv* env, jsi::Runtime& runtime, const jsi::String& string) {
@@ -218,6 +231,40 @@ void runReportingErrors(Runtime& runtime, Work work) {
218
231
  }
219
232
  }
220
233
 
234
+ // ---------- Blobs ----------
235
+
236
+ // What __blobCollector returns: when the garbage collector collects it (with the last Blob that holds it),
237
+ // it releases the blob's native bytes through blobRelease.
238
+ class BlobCollector : public jsi::HostObject {
239
+ public:
240
+ BlobCollector(jobject owner, jint releaseIndex, std::string blobId)
241
+ : owner_(owner), releaseIndex_(releaseIndex), blobId_(std::move(blobId)) {}
242
+
243
+ ~BlobCollector() override {
244
+ callNativeWithString(owner_, releaseIndex_, blobId_);
245
+ }
246
+
247
+ private:
248
+ jobject owner_;
249
+ jint releaseIndex_;
250
+ std::string blobId_;
251
+ };
252
+
253
+ void installBlobCollector(jsi::Runtime& runtime, jobject owner, jint releaseIndex) {
254
+ auto collector = [owner, releaseIndex](jsi::Runtime& runtime, const jsi::Value&, const jsi::Value* arguments, size_t count) {
255
+ if (count < 1 || !arguments[0].isString()) throw jsi::JSError(runtime, "__blobCollector needs a blob id");
256
+
257
+ auto blobCollector = std::make_shared<BlobCollector>(owner, releaseIndex, arguments[0].getString(runtime).utf8(runtime));
258
+
259
+ return jsi::Value(runtime, jsi::Object::createFromHostObject(runtime, blobCollector));
260
+ };
261
+
262
+ runtime.global().setProperty(
263
+ runtime,
264
+ "__blobCollector",
265
+ jsi::Function::createFromHostFunction(runtime, jsi::PropNameID::forAscii(runtime, "__blobCollector"), 1, collector));
266
+ }
267
+
221
268
  // ---------- __native ----------
222
269
 
223
270
  // A Kotlin exception thrown by a native function becomes a JS error at the call site.
@@ -273,6 +320,7 @@ void installNativeModule(Runtime& runtime, JNIEnv* env, jobjectArray functionNam
273
320
  auto name = static_cast<jstring>(env->GetObjectArrayElement(functionNames, index));
274
321
  std::string functionName = toStdString(env, name);
275
322
  nativeModule.setProperty(hermes, functionName.c_str(), nativeFunction(hermes, runtime.owner, functionName, index));
323
+ if (functionName == "blobRelease") installBlobCollector(hermes, runtime.owner, index);
276
324
  env->DeleteLocalRef(name);
277
325
  }
278
326
 
@@ -390,6 +438,7 @@ extern "C" JNIEXPORT void JNICALL Java_dev_nativue_JavaScriptRuntime_call(
390
438
 
391
439
  extern "C" JNIEXPORT void JNICALL Java_dev_nativue_JavaScriptRuntime_destroy(JNIEnv* env, jobject, jlong handle) {
392
440
  Runtime* runtime = reinterpret_cast<Runtime*>(handle);
441
+ runtime->hermes.reset(); // first: collecting its Blobs on the way out still calls the owner
393
442
  env->DeleteGlobalRef(runtime->owner);
394
443
  delete runtime;
395
444
  }
@@ -0,0 +1,72 @@
1
+ package dev.nativue
2
+
3
+ import android.util.Base64
4
+ import java.io.ByteArrayOutputStream
5
+ import java.util.UUID
6
+ import java.util.concurrent.ConcurrentHashMap
7
+
8
+ /**
9
+ * The bytes behind JS's Blobs, by id. JS holds only the id; the runtime releases it when the garbage
10
+ * collector collects the last Blob pointing to it. Used from the JS thread and from Networking's.
11
+ * Mirrors ios/BlobStore.swift.
12
+ */
13
+ class BlobStore private constructor() {
14
+ private val bytesById = ConcurrentHashMap<String, ByteArray>()
15
+
16
+ fun store(bytes: ByteArray): String {
17
+ val blobId = UUID.randomUUID().toString()
18
+ bytesById[blobId] = bytes
19
+
20
+ return blobId
21
+ }
22
+
23
+ /** A slice of a blob's bytes; null if it's been released. */
24
+ fun bytes(blobId: String, offset: Int, size: Int): ByteArray? {
25
+ val bytes = bytesById[blobId] ?: return null
26
+ if (offset < 0 || size < 0 || offset + size > bytes.size) return null
27
+
28
+ return bytes.copyOfRange(offset, offset + size)
29
+ }
30
+
31
+ /** `{ blobId, offset, size }`, as JS describes the bytes it sends. */
32
+ fun bytes(blob: Map<*, *>): ByteArray? {
33
+ val blobId = blob["blobId"] as? String ?: return null
34
+
35
+ return bytes(blobId, (blob["offset"] as? Number)?.toInt() ?: 0, (blob["size"] as? Number)?.toInt() ?: 0)
36
+ }
37
+
38
+ /** A `blob:<id>?offset=…&size=…` URL, from URL.createObjectURL. */
39
+ fun bytes(url: String): ByteArray? {
40
+ if (!url.startsWith("blob:")) return null
41
+
42
+ val blobId = url.removePrefix("blob:").substringBefore("?")
43
+ val parameters = url.substringAfter("?", "").split("&").associate { it.substringBefore("=") to it.substringAfter("=", "") }
44
+
45
+ return bytes(blobId, parameters["offset"]?.toIntOrNull() ?: 0, parameters["size"]?.toIntOrNull() ?: 0)
46
+ }
47
+
48
+ fun remove(blobId: String) {
49
+ bytesById.remove(blobId)
50
+ }
51
+
52
+ /** On reload: the Blobs' JS is gone. */
53
+ fun removeAll() = bytesById.clear()
54
+
55
+ /** Joins `{ string }`, `{ base64 }` and `{ blob }` parts into a new blob; null if a part's blob was released. */
56
+ fun create(parts: List<*>): Pair<String, Int>? {
57
+ val joined = ByteArrayOutputStream()
58
+
59
+ for (part in parts.filterIsInstance<Map<*, *>>()) {
60
+ (part["string"] as? String)?.let { joined.write(it.toByteArray()) }
61
+ (part["base64"] as? String)?.let { joined.write(Base64.decode(it, Base64.DEFAULT)) }
62
+ (part["blob"] as? Map<*, *>)?.let { joined.write(bytes(it) ?: return null) }
63
+ }
64
+
65
+ return store(joined.toByteArray()) to joined.size()
66
+ }
67
+
68
+ companion object {
69
+ /** One for the app: <Image> reads `blob:` URLs from it too. */
70
+ val shared = BlobStore()
71
+ }
72
+ }
@@ -12,6 +12,7 @@ import android.os.Looper
12
12
  import android.text.Editable
13
13
  import android.text.InputType
14
14
  import android.text.TextWatcher
15
+ import android.util.Base64
15
16
  import android.util.Log
16
17
  import android.util.TypedValue
17
18
  import android.view.Gravity
@@ -69,6 +70,10 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
69
70
  private val modalHostsByNodeId = HashMap<Int, ModalHost>()
70
71
  private val gestureReportersByNodeId = HashMap<Int, GestureReporter>()
71
72
  /** Views with @layout, and the box they last reported. */
73
+ private val blobStore = BlobStore.shared
74
+ private val networking = Networking(activity, blobStore) { owner, requestId, eventName, payload ->
75
+ callIfStillRunning(owner, "__networkEvent", requestId, eventName, payload)
76
+ }
72
77
  private val reportedLayoutsByNodeId = mutableMapOf<Int, Map<String, Float>?>()
73
78
 
74
79
  /** The latest window insets, mid-animation while the keyboard moves. */
@@ -361,7 +366,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
361
366
  putAll(storageFunctions())
362
367
  putAll(animatedFunctions())
363
368
  putAll(layoutAnimationFunctions())
364
- putAll(fetchFunctions())
369
+ putAll(networkingFunctions())
370
+ putAll(blobFunctions())
365
371
  }
366
372
 
367
373
  /** Read from JS, off the main thread: the window's size doesn't need the views. */
@@ -428,49 +434,32 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
428
434
  "configureNextLayoutAnimation" to { arguments -> nextLayoutAnimation = arguments[0] as? Map<*, *> },
429
435
  )
430
436
 
437
+ /** XMLHttpRequest's native side (Networking); fetch is built on it in JS. */
438
+ private fun networkingFunctions(): Map<String, NativeFunction> = mapOf(
439
+ "sendRequest" to { arguments ->
440
+ networking.send((arguments[0] as Number).toInt(), arguments[1] as? Map<*, *> ?: emptyMap<String, Any>(), runtime)
441
+ },
442
+ "abortRequest" to { arguments -> networking.abort((arguments[0] as Number).toInt()) },
443
+ )
444
+
431
445
  /**
432
- * fetch: HttpURLConnection runs the request; JS hears back through
433
- * __fetchFinished(requestId, response, error).
446
+ * The bytes behind JS's Blobs (BlobStore). blobRelease is also what the runtime calls when a Blob is
447
+ * garbage collected.
434
448
  */
435
- // Limitation: Text bodies only (no binary, FormData or streaming) and no abort, like on iOS.
436
- private fun fetchFunctions(): Map<String, NativeFunction> = mapOf(
437
- "fetch" to { arguments ->
438
- val requestId = arguments[0]
439
- val url = arguments[1] as String
440
- val method = arguments[2] as String
441
- val headers = arguments[3] as? Map<*, *> ?: emptyMap<String, String>()
442
- val body = arguments[4] as? String
443
- val owner = runtime
444
-
445
- thread {
446
- val (response, error) = runCatching { request(url, method, headers, body) }
447
- .fold({ Pair(it, null) }, { Pair(null, it.message ?: it.toString()) })
448
- callIfStillRunning(owner, "__fetchFinished", requestId, response, error)
449
+ private fun blobFunctions(): Map<String, NativeFunction> = mapOf(
450
+ // null when a part's blob has been released.
451
+ "blobCreate" to { arguments ->
452
+ blobStore.create(arguments[0] as? List<*> ?: emptyList<Any>())?.let { (blobId, size) -> mapOf("blobId" to blobId, "size" to size) }
453
+ },
454
+ "blobRead" to { arguments ->
455
+ val (blobId, offset, size) = Triple(arguments[0] as String, (arguments[1] as Number).toInt(), (arguments[2] as Number).toInt())
456
+ blobStore.bytes(blobId, offset, size)?.let { bytes ->
457
+ if (arguments[3] == "base64") Base64.encodeToString(bytes, Base64.NO_WRAP) else String(bytes, Charsets.UTF_8)
449
458
  }
450
459
  },
460
+ "blobRelease" to { arguments -> blobStore.remove(arguments[0] as String) },
451
461
  )
452
462
 
453
- private fun request(url: String, method: String, headers: Map<*, *>, body: String?): Map<String, Any> {
454
- val connection = URL(url).openConnection() as HttpURLConnection
455
- connection.requestMethod = method
456
- headers.forEach { (name, value) -> connection.setRequestProperty(name.toString(), value.toString()) }
457
-
458
- if (body != null) {
459
- connection.doOutput = true
460
- connection.outputStream.use { it.write(body.toByteArray()) }
461
- }
462
-
463
- val status = connection.responseCode
464
- val stream = if (status >= 400) connection.errorStream else connection.inputStream
465
- val responseHeaders = connection.headerFields.filterKeys { it != null }.mapValues { it.value.joinToString(", ") }
466
-
467
- return mapOf(
468
- "status" to status,
469
- "headers" to responseHeaders,
470
- "body" to (stream?.bufferedReader()?.use { it.readText() } ?: ""),
471
- )
472
- }
473
-
474
463
  // ---------- Errors ----------
475
464
 
476
465
  /** Errors outside Vue (timers, the bundle itself) come from bridge.cpp; Vue's through `__native`. */
@@ -563,6 +552,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
563
552
  }
564
553
  modalHostsByNodeId.clear()
565
554
  gestureReportersByNodeId.clear() // node ids start over
555
+ networking.abortAll() // and so do request ids
556
+ blobStore.removeAll() // and the Blobs that held them are gone
566
557
  reportedLayoutsByNodeId.clear()
567
558
  animatedGraph.reset()
568
559
  animatedGraph.onAnimationEnd = { animationId, finished ->
@@ -836,6 +827,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
836
827
  "horizontal" -> setScrollDirection(node, isTruthyAttribute(value))
837
828
 
838
829
  "pagingEnabled" -> (view as? ScrollContainerView)?.pagingEnabled = isTruthyAttribute(value)
830
+ "scrollEventThrottle" -> (view as? ScrollContainerView)?.scrollEventThrottle = (value as? Number)?.toLong() ?: 0
839
831
 
840
832
  "showsHorizontalScrollIndicator" -> (view as? ScrollContainerView)?.showsHorizontalScrollIndicator = isTruthyAttribute(value)
841
833
 
@@ -0,0 +1,323 @@
1
+ package dev.nativue
2
+
3
+ import android.content.Context
4
+ import android.net.Uri
5
+ import android.util.Base64
6
+ import android.webkit.CookieManager
7
+ import java.io.ByteArrayOutputStream
8
+ import java.io.File
9
+ import java.io.FilterInputStream
10
+ import java.io.IOException
11
+ import java.io.InputStream
12
+ import java.io.InputStreamReader
13
+ import java.io.OutputStream
14
+ import java.net.HttpURLConnection
15
+ import java.net.SocketTimeoutException
16
+ import java.net.URL
17
+ import java.util.UUID
18
+ import java.util.concurrent.ConcurrentHashMap
19
+ import kotlin.concurrent.thread
20
+
21
+ /**
22
+ * HTTP requests for XMLHttpRequest (and fetch, built on it), each on its own thread with HttpURLConnection.
23
+ * Their progress comes back as events (see NetworkEventPayloads in types.ts), which the Bridge hands to
24
+ * JS's __networkEvent. Mirrors ios/Networking.swift.
25
+ */
26
+ class Networking(
27
+ private val context: Context,
28
+ private val blobStore: BlobStore,
29
+ private val onEvent: (owner: JavaScriptRuntime?, requestId: Int, eventName: String, payload: Map<String, Any?>) -> Unit,
30
+ ) {
31
+ private class Request(val id: Int, val owner: JavaScriptRuntime?, query: Map<*, *>) {
32
+ /** 'text', 'base64' or 'blob'. */
33
+ val responseType = query["responseType"] as? String ?: "text"
34
+ val incrementalUpdates = query["incrementalUpdates"] == true
35
+ val streamsText = incrementalUpdates && responseType == "text"
36
+ val withCredentials = query["withCredentials"] != false
37
+
38
+ @Volatile var aborted = false
39
+ @Volatile var connection: HttpURLConnection? = null
40
+ }
41
+
42
+ /** What a request sends, read as it uploads; a length of -1 when unknown. */
43
+ private class Body(
44
+ val length: Long,
45
+ val contentType: String? = null,
46
+ val temporaryFile: File? = null,
47
+ val open: () -> InputStream,
48
+ )
49
+
50
+ private val requestsById = ConcurrentHashMap<Int, Request>()
51
+
52
+ /** The system's, shared with WebViews and kept on disk. Null on a device without a WebView. */
53
+ private val cookies by lazy { runCatching { CookieManager.getInstance() }.getOrNull() }
54
+
55
+ fun send(requestId: Int, query: Map<*, *>, owner: JavaScriptRuntime?) {
56
+ val request = Request(requestId, owner, query)
57
+ requestsById[requestId] = request
58
+
59
+ thread {
60
+ runCatching { perform(request, query) }.onFailure { error ->
61
+ val failure = mapOf("error" to (error.message ?: error.toString()), "timedOut" to (error is SocketTimeoutException))
62
+ emit(request, "complete", failure)
63
+ }
64
+ requestsById.remove(requestId, request)
65
+ }
66
+ }
67
+
68
+ /** JS has already settled the request: nothing more is reported for it. */
69
+ fun abort(requestId: Int) {
70
+ requestsById.remove(requestId)?.let(::cancel)
71
+ }
72
+
73
+ /** On reload: the requests' JS is gone. */
74
+ fun abortAll() {
75
+ requestsById.values.forEach(::cancel)
76
+ requestsById.clear()
77
+ }
78
+
79
+ private fun cancel(request: Request) {
80
+ request.aborted = true
81
+ request.connection?.disconnect()
82
+ }
83
+
84
+ private fun emit(request: Request, eventName: String, payload: Map<String, Any?>) {
85
+ if (!request.aborted) onEvent(request.owner, request.id, eventName, payload)
86
+ }
87
+
88
+ private fun perform(request: Request, query: Map<*, *>) {
89
+ val body = (query["body"] as? Map<*, *>)?.let(::body)
90
+
91
+ try {
92
+ perform(request, query, body)
93
+ } finally {
94
+ body?.temporaryFile?.delete()
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Follows redirects itself, like a browser: so each hop's cookies are kept and sent, and http to https
100
+ * redirects (which HttpURLConnection won't follow) work.
101
+ */
102
+ private fun perform(request: Request, query: Map<*, *>, body: Body?) {
103
+ val firstUrl = URL(query["url"] as String)
104
+ var url = firstUrl
105
+ var method = query["method"] as? String ?: "GET"
106
+ var sentBody = body
107
+
108
+ repeat(MAX_REDIRECTS + 1) {
109
+ val headers = (query["headers"] as? Map<*, *>).orEmpty()
110
+ .filterKeys { url.sameOrigin(firstUrl) || !it.toString().equals("Authorization", ignoreCase = true) }
111
+ val connection = connect(request, url, method, headers, (query["timeout"] as? Number)?.toInt() ?: 0)
112
+ if (sentBody != null) upload(request, connection, sentBody)
113
+
114
+ val status = connection.responseCode
115
+ if (request.withCredentials) storeCookies(connection)
116
+ val location = connection.getHeaderField("Location")
117
+ if (status !in REDIRECT_STATUSES || location == null) return respond(request, connection, status)
118
+
119
+ connection.disconnect()
120
+ url = URL(url, location)
121
+ // As browsers do: 303, and 301/302 after a POST, become a GET without the body.
122
+ if (status == 303 || (status != 307 && status != 308 && method == "POST")) {
123
+ method = "GET"
124
+ sentBody = null
125
+ }
126
+ }
127
+ throw IOException("too many redirects")
128
+ }
129
+
130
+ private fun connect(request: Request, url: URL, method: String, headers: Map<*, *>, timeout: Int): HttpURLConnection {
131
+ val connection = url.openConnection() as HttpURLConnection
132
+ request.connection = connection
133
+ if (request.aborted) throw IOException("aborted")
134
+
135
+ connection.instanceFollowRedirects = false
136
+ connection.requestMethod = method
137
+ connection.connectTimeout = timeout
138
+ connection.readTimeout = timeout
139
+ headers.forEach { (name, value) -> connection.setRequestProperty(name.toString(), value.toString()) }
140
+ if (request.withCredentials) sendCookies(connection)
141
+
142
+ return connection
143
+ }
144
+
145
+ private fun URL.sameOrigin(other: URL) = protocol == other.protocol && host == other.host && port == other.port
146
+
147
+ private fun respond(request: Request, connection: HttpURLConnection, status: Int) {
148
+ val headers = connection.headerFields.filterKeys { it != null }.mapValues { it.value.joinToString(", ") }
149
+ emit(request, "response", mapOf("status" to status, "headers" to headers, "url" to connection.url.toString()))
150
+
151
+ val stream = (if (status >= 400) connection.errorStream else connection.inputStream) ?: ByteArray(0).inputStream()
152
+ download(request, CountingInputStream(stream), connection.contentLengthLong, connection.contentType)
153
+ emit(request, "complete", mapOf("error" to null, "timedOut" to false))
154
+ }
155
+
156
+ private fun sendCookies(connection: HttpURLConnection) {
157
+ val cookie = cookies?.getCookie(connection.url.toString()) ?: return
158
+
159
+ connection.setRequestProperty("Cookie", cookie)
160
+ }
161
+
162
+ private fun storeCookies(connection: HttpURLConnection) {
163
+ val cookies = cookies ?: return
164
+ val url = connection.url.toString()
165
+
166
+ connection.headerFields
167
+ .filterKeys { it.equals("Set-Cookie", ignoreCase = true) }
168
+ .values.flatten()
169
+ .forEach { cookies.setCookie(url, it) }
170
+ cookies.flush()
171
+ }
172
+
173
+ /** What to send, or null for none. */
174
+ private fun body(body: Map<*, *>): Body? {
175
+ (body["string"] as? String)?.let { return bytesBody(it.toByteArray()) }
176
+ (body["base64"] as? String)?.let { return bytesBody(Base64.decode(it, Base64.DEFAULT)) }
177
+ (body["blob"] as? Map<*, *>)?.let { return bytesBody(blobBytes(it)) }
178
+ (body["uri"] as? String)?.let { uri -> return Body(-1) { openUri(uri) } }
179
+
180
+ val parts = (body["formData"] as? List<*>)?.filterIsInstance<Map<*, *>>() ?: return null
181
+ val boundary = "nativue-${UUID.randomUUID()}"
182
+ val file = writeMultipartBody(parts, boundary)
183
+
184
+ return Body(file.length(), "multipart/form-data; boundary=$boundary", file) { file.inputStream() }
185
+ }
186
+
187
+ private fun bytesBody(bytes: ByteArray) = Body(bytes.size.toLong()) { bytes.inputStream() }
188
+
189
+ /** In chunks, so `xhr.upload.onprogress` can follow and a large file never sits in memory. */
190
+ private fun upload(request: Request, connection: HttpURLConnection, body: Body) {
191
+ connection.doOutput = true
192
+ body.contentType?.let { connection.setRequestProperty("Content-Type", it) }
193
+ if (body.length >= 0) connection.setFixedLengthStreamingMode(body.length) else connection.setChunkedStreamingMode(CHUNK_SIZE)
194
+
195
+ var loaded = 0L
196
+ body.open().use { input ->
197
+ connection.outputStream.use { output ->
198
+ val buffer = ByteArray(CHUNK_SIZE)
199
+ while (true) {
200
+ val length = input.read(buffer)
201
+ if (length < 0) break
202
+ output.write(buffer, 0, length)
203
+ loaded += length
204
+ emit(request, "uploadprogress", mapOf("loaded" to loaded, "total" to body.length))
205
+ }
206
+ }
207
+ }
208
+ }
209
+
210
+ private fun download(request: Request, stream: CountingInputStream, expectedLength: Long, contentType: String?) {
211
+ fun progress() = mapOf("loaded" to stream.count, "total" to expectedLength)
212
+
213
+ if (request.streamsText) {
214
+ // The reader keeps a character split between chunks for the next one.
215
+ InputStreamReader(stream, Charsets.UTF_8).use { reader ->
216
+ val buffer = CharArray(CHUNK_SIZE)
217
+ while (true) {
218
+ val length = reader.read(buffer)
219
+ if (length < 0) break
220
+ emit(request, "incrementaldata", progress() + ("text" to String(buffer, 0, length)))
221
+ }
222
+ }
223
+ return
224
+ }
225
+
226
+ val bytes = ByteArrayOutputStream()
227
+ stream.use {
228
+ val buffer = ByteArray(CHUNK_SIZE)
229
+ while (true) {
230
+ val length = it.read(buffer)
231
+ if (length < 0) break
232
+ bytes.write(buffer, 0, length)
233
+ if (request.incrementalUpdates) emit(request, "progress", progress())
234
+ }
235
+ }
236
+
237
+ emit(request, "data", mapOf("data" to responseData(request, bytes.toByteArray(), contentType)))
238
+ }
239
+
240
+ /** Text, base64, or for 'blob' the bytes kept in the BlobStore, described as a NativeBlob. */
241
+ private fun responseData(request: Request, bytes: ByteArray, contentType: String?): Any = when (request.responseType) {
242
+ "base64" -> Base64.encodeToString(bytes, Base64.NO_WRAP)
243
+ "blob" -> {
244
+ val type = contentType?.substringBefore(";")?.trim().orEmpty()
245
+ mapOf("blobId" to blobStore.store(bytes), "offset" to 0, "size" to bytes.size, "type" to type)
246
+ }
247
+ else -> String(bytes, Charsets.UTF_8)
248
+ }
249
+
250
+ /**
251
+ * multipart/form-data, written to a temporary file: text fields as they are, files copied from their uri
252
+ * (content:, file: or data:), so a large video never sits in memory.
253
+ */
254
+ private fun writeMultipartBody(parts: List<Map<*, *>>, boundary: String): File {
255
+ val file = File.createTempFile("nativue-upload-", null, context.cacheDir)
256
+
257
+ try {
258
+ file.outputStream().buffered().use { writeMultipartParts(parts, boundary, it) }
259
+ } catch (error: Throwable) {
260
+ file.delete()
261
+ throw error
262
+ }
263
+
264
+ return file
265
+ }
266
+
267
+ private fun writeMultipartParts(parts: List<Map<*, *>>, boundary: String, body: OutputStream) {
268
+ fun write(text: String) = body.write(text.toByteArray())
269
+
270
+ for (part in parts) {
271
+ val name = part["name"] as? String ?: ""
272
+ write("--$boundary\r\n")
273
+
274
+ val value = part["value"] as? String
275
+ if (value != null) {
276
+ write("Content-Disposition: form-data; name=\"$name\"\r\n\r\n$value\r\n")
277
+ continue
278
+ }
279
+
280
+ val uri = part["uri"] as? String
281
+ val blob = part["blob"] as? Map<*, *>
282
+ if (uri == null && blob == null) continue
283
+
284
+ val filename = part["filename"] as? String ?: "file"
285
+ val type = part["type"] as? String ?: "application/octet-stream"
286
+ write("Content-Disposition: form-data; name=\"$name\"; filename=\"$filename\"\r\n")
287
+ write("Content-Type: $type\r\n\r\n")
288
+ if (uri != null) openUri(uri).use { it.copyTo(body) }
289
+ if (blob != null) body.write(blobBytes(blob))
290
+ write("\r\n")
291
+ }
292
+ write("--$boundary--\r\n")
293
+ }
294
+
295
+ private fun blobBytes(blob: Map<*, *>) = blobStore.bytes(blob) ?: throw IOException("The blob has been released")
296
+
297
+ private fun openUri(uri: String): InputStream {
298
+ if (uri.startsWith("data:")) return Base64.decode(uri.substringAfter(","), Base64.DEFAULT).inputStream()
299
+
300
+ return context.contentResolver.openInputStream(Uri.parse(uri)) ?: throw IllegalArgumentException("can't read $uri")
301
+ }
302
+
303
+ /** Counts the bytes read, for download progress. */
304
+ private class CountingInputStream(stream: InputStream) : FilterInputStream(stream) {
305
+ var count = 0L
306
+ private set
307
+
308
+ override fun read(): Int = super.read().also { if (it >= 0) count++ }
309
+
310
+ override fun read(buffer: ByteArray, offset: Int, length: Int): Int =
311
+ super.read(buffer, offset, length).also { if (it > 0) count += it }
312
+ }
313
+
314
+ companion object {
315
+ /** 64 KB: progress often enough, without an event per few bytes. */
316
+ private const val CHUNK_SIZE = 64 * 1024
317
+
318
+ /** Browsers stop at 20 too. */
319
+ private const val MAX_REDIRECTS = 20
320
+
321
+ private val REDIRECT_STATUSES = setOf(301, 302, 303, 307, 308)
322
+ }
323
+ }
@@ -7,6 +7,7 @@ import android.graphics.BitmapFactory
7
7
  import android.graphics.Rect
8
8
  import android.os.Handler
9
9
  import android.os.Looper
10
+ import android.os.SystemClock
10
11
  import android.util.Base64
11
12
  import android.util.LruCache
12
13
  import android.view.MotionEvent
@@ -21,6 +22,7 @@ import android.widget.ProgressBar
21
22
  import android.widget.ScrollView
22
23
  import android.widget.Switch
23
24
  import java.io.File
25
+ import java.io.IOException
24
26
  import java.net.URL
25
27
  import java.security.MessageDigest
26
28
  import java.util.concurrent.Executors
@@ -185,6 +187,12 @@ class ScrollContainerView(context: Context) : ContainerView(context) {
185
187
  var onScroll: ((x: Int, y: Int) -> Unit)? = null
186
188
  var onOffsetChange: ((x: Int, y: Int) -> Unit)? = null
187
189
 
190
+ /** scroll-event-throttle, in milliseconds: 0 reports every scroll step. */
191
+ var scrollEventThrottle = 0L
192
+
193
+ private var lastReportTime = 0L
194
+ private var hasPendingReport = false
195
+
188
196
  var pagingEnabled = false
189
197
  set(value) {
190
198
  field = value
@@ -359,6 +367,25 @@ class ScrollContainerView(context: Context) : ContainerView(context) {
359
367
  refreshIndicator.layout(indicatorLeft, -size, indicatorLeft + size, 0)
360
368
  }
361
369
 
370
+ // Within the throttle, the report waits for its end, so the last position always reaches JS.
371
+ private fun reportScrollThrottled() {
372
+ if (onScroll == null || hasPendingReport) return
373
+
374
+ val elapsed = SystemClock.uptimeMillis() - lastReportTime
375
+ if (elapsed >= scrollEventThrottle) return reportScroll()
376
+
377
+ hasPendingReport = true
378
+ postDelayed({
379
+ hasPendingReport = false
380
+ reportScroll()
381
+ }, scrollEventThrottle - elapsed)
382
+ }
383
+
384
+ private fun reportScroll() {
385
+ lastReportTime = SystemClock.uptimeMillis()
386
+ onScroll?.invoke(scroller.scrollX, scroller.scrollY)
387
+ }
388
+
362
389
  private fun makeScroller(horizontal: Boolean): FrameLayout {
363
390
  val scroller = if (horizontal) PagingHorizontalScrollView(context) else PagingVerticalScrollView(context)
364
391
  (scroller as PagingScroller).pagingEnabled = pagingEnabled
@@ -368,7 +395,7 @@ class ScrollContainerView(context: Context) : ContainerView(context) {
368
395
  scroller.addView(content, FrameLayout.LayoutParams(content.layoutParams?.width ?: 0, content.layoutParams?.height ?: 0))
369
396
  scroller.setOnScrollChangeListener { _, x, y, _, _ ->
370
397
  onOffsetChange?.invoke(x, y)
371
- onScroll?.invoke(x, y)
398
+ reportScrollThrottled()
372
399
  if (isTouching && keyboardDismissMode != "none") rootView.findFocus()?.let(::hideKeyboard)
373
400
  }
374
401
 
@@ -535,7 +562,7 @@ class RemoteImageView(context: Context) : ImageView(context) {
535
562
  if (cachePolicy == "none") return
536
563
 
537
564
  decodedImages.put(source, bitmap)
538
- if (cachePolicy != "disk" || downloadedBytes == null || source.startsWith("data:")) return
565
+ if (cachePolicy != "disk" || downloadedBytes == null || isInMemory(source)) return
539
566
 
540
567
  loader.execute { diskCache.write(source, downloadedBytes) }
541
568
  }
@@ -578,8 +605,12 @@ class RemoteImageView(context: Context) : ImageView(context) {
578
605
  setMeasuredDimension(measuredWidth.roundToInt(), measuredHeight.roundToInt())
579
606
  }
580
607
 
608
+ /** data: and blob: images are already on the device: nothing to keep on disk. */
609
+ private fun isInMemory(source: String) = source.startsWith("data:") || source.startsWith("blob:")
610
+
581
611
  private fun download(source: String): ByteArray {
582
612
  if (source.startsWith("data:")) return Base64.decode(source.substringAfter(","), Base64.DEFAULT)
613
+ if (source.startsWith("blob:")) return BlobStore.shared.bytes(source) ?: throw IOException("The blob has been released")
583
614
 
584
615
  return URL(source).openStream().use { it.readBytes() }
585
616
  }