@tokamakdev/platform-android-arm64 0.1.1-beta.106 → 0.1.1-beta.112

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.
@@ -156,6 +156,11 @@ plugins {
156
156
  android {
157
157
  namespace 'com.tokamak.runtime.plugin'
158
158
  }
159
+
160
+ // Plugins mark code that needs a later API level with RequiresApi, which lint checks.
161
+ dependencies {
162
+ api 'androidx.annotation:annotation:1.9.1'
163
+ }
159
164
  EOF
160
165
 
161
166
  has_icon=false
@@ -182,13 +187,21 @@ raw_names=" "
182
187
  for plugin in "$input/plugins"/*/; do
183
188
  plugin_id=$(basename "$plugin")
184
189
  class=$(cat "$plugin/class" 2>/dev/null || true)
185
- if [[ ! "$class" =~ $kotlin_class ]]; then
186
- echo "plugin '$plugin_id' has invalid android class '$class'" >&2
187
- exit 1
190
+ # A plugin whose native code is its generated bindings alone has no class.
191
+ if [[ -n "$class" || ! -d "$plugin/bindings" ]]; then
192
+ if [[ ! "$class" =~ $kotlin_class ]]; then
193
+ echo "plugin '$plugin_id' has invalid android class '$class'" >&2
194
+ exit 1
195
+ fi
196
+ printf ' %s(app.host("%s")),\n' "$class" "$plugin_id" >> "$registry"
188
197
  fi
189
- printf ' %s(app.host("%s")),\n' "$class" "$plugin_id" >> "$registry"
190
198
  module=$plugin_modules/$plugin_id
191
199
  mkdir -p "$module/src/main/kotlin"
200
+ # `tok bindings` names the generated class com.tokamak.bindings.<id>.Bindings, with - as _.
201
+ for source in "$plugin/bindings"/*.kt; do
202
+ printf ' com.tokamak.bindings.%s.Bindings(app.host("%s")),\n' "${plugin_id//-/_}" "$plugin_id" >> "$registry"
203
+ cp "$source" "$module/src/main/kotlin/TokamakBindings.kt"
204
+ done
192
205
  for source in "$plugin/sources"/*; do
193
206
  case "$source" in
194
207
  *.kt)
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/android-arm64/lib/TokamakRuntime/libtokamak.a
3
- size: 34952756 bytes
4
- sha256: a6e8f421eda04df911bf1fbc77ddc94439ecc3924b6249c950cc851000e993ed
3
+ size: 35457770 bytes
4
+ sha256: 27b2e0b78045287fd566b7c946db423d82726e604feede39bb4d3f45d0345d97
@@ -21,8 +21,8 @@ private const val UNSUPPORTED =
21
21
  class TokamakActivity : Activity() {
22
22
  private val tokamak: TokamakApplication
23
23
  get() = application as TokamakApplication
24
- private lateinit var webView: WebView
25
- private lateinit var pluginBridge: TokamakPluginBridge
24
+ internal lateinit var webView: WebView
25
+ private set
26
26
  private var runtime: TokamakRuntime? = null
27
27
  private var proxyPort: Int? = null
28
28
  private var restoreGeneration = 0L
@@ -37,10 +37,6 @@ class TokamakActivity : Activity() {
37
37
  settings.setSupportMultipleWindows(false)
38
38
  }
39
39
  webView.webChromeClient = TokamakWebChromeClient(tokamak, tokamak.appHost)
40
- pluginBridge = TokamakPluginBridge(this, tokamak.appHost, tokamak.plugins)
41
- if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
42
- pluginBridge.install(webView)
43
- }
44
40
  setContentView(webViewContainer())
45
41
  // A recreated activity or one reopened from Recents carries an intent plugins have had.
46
42
  val launchedFromHistory = intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0
@@ -71,7 +67,6 @@ class TokamakActivity : Activity() {
71
67
  if (tokamak.activity === this) tokamak.activity = null
72
68
  if (isFinishing) tokamak.permissionRequests.cancel()
73
69
  TokamakProxy.release(this)
74
- pluginBridge.close()
75
70
  webView.stopLoading()
76
71
  webView.destroy()
77
72
  super.onDestroy()
@@ -134,14 +129,13 @@ class TokamakActivity : Activity() {
134
129
  if (destroyed) return
135
130
  val runtime = runtime ?: return
136
131
  webView.webViewClient =
137
- TokamakWebViewClient(this, tokamak.appHost, runtime, pluginBridge)
132
+ TokamakWebViewClient(this, tokamak.appHost, runtime)
138
133
  webView.loadUrl("https://${tokamak.appHost}/")
139
134
  }
140
135
 
141
136
  private fun proxyIsSupported(): Boolean =
142
137
  WebViewFeature.isFeatureSupported(WebViewFeature.PROXY_OVERRIDE) &&
143
- WebViewFeature.isFeatureSupported(WebViewFeature.PROXY_OVERRIDE_REVERSE_BYPASS) &&
144
- WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)
138
+ WebViewFeature.isFeatureSupported(WebViewFeature.PROXY_OVERRIDE_REVERSE_BYPASS)
145
139
 
146
140
  private fun show(html: String) = webView.loadData(html, "text/html", "utf-8")
147
141
 
@@ -12,7 +12,6 @@ import androidx.lifecycle.LifecycleOwner
12
12
  import androidx.lifecycle.ProcessLifecycleOwner
13
13
  import java.io.File
14
14
  import java.util.concurrent.Executors
15
- import org.json.JSONTokener
16
15
 
17
16
  private const val HOST_METADATA = "tokamak.host"
18
17
  private const val DEV_ENDPOINT_METADATA = "tokamak.dev.endpoint"
@@ -33,6 +32,7 @@ class TokamakApplication : Application(), TokamakPlugins {
33
32
  /** Every plugin, by ID. */
34
33
  val plugins: Map<String, TokamakPlugin> by lazy {
35
34
  buildMap {
35
+ put("tokamak", TokamakCorePlugin(this@TokamakApplication))
36
36
  tokamakPlugins(this@TokamakApplication).forEach { plugin ->
37
37
  check(put(plugin.id, plugin) == null) { "Duplicate plugin ID" }
38
38
  }
@@ -41,28 +41,32 @@ class TokamakApplication : Application(), TokamakPlugins {
41
41
 
42
42
  internal val permissionRequests = TokamakPermissions(this)
43
43
 
44
+ internal val resources = TokamakResources()
45
+
44
46
  private val started = lazy(::startRuntime)
45
47
 
46
48
  /** The running runtime, started on first use. Blocks while it starts. */
47
49
  internal val runtime: TokamakRuntime by started
48
50
 
49
- /** The Worker's calls and subscriptions on the plugins. Main thread only. */
50
- private val workerRequests by lazy {
51
- TokamakPluginRequests<Long>(plugins) { id, result -> runtime.reply(id, result.toString()) }
52
- }
51
+ private lateinit var workerRequests: TokamakPluginRequests<Long>
53
52
 
54
53
  /** The plugins as the runtime calls them, on its own threads. */
55
54
  private val workerPlugins =
56
55
  object : TokamakRuntime.Plugins {
57
- override fun call(id: Long, plugin: String, method: String, arguments: String) =
58
- mainExecutor.execute { workerRequests.run(id, false, plugin, method, parse(arguments)) }
56
+ override fun call(id: Long, plugin: String, method: String, payload: ByteArray) =
57
+ workerRequests.run(id, TokamakPluginRequest.CALL, plugin, method, payload)
58
+
59
+ override fun callWithBody(id: Long, plugin: String, method: String, payload: ByteArray) =
60
+ workerRequests.run(id, TokamakPluginRequest.CALL_WITH_BODY, plugin, method, payload)
59
61
 
60
- override fun subscribe(id: Long, plugin: String, method: String, arguments: String) =
61
- mainExecutor.execute { workerRequests.run(id, true, plugin, method, parse(arguments)) }
62
+ override fun chunk(id: Long, payload: ByteArray, failed: Boolean, done: Boolean) =
63
+ workerRequests.chunk(id, TokamakPluginResult(payload, failed, done))
62
64
 
63
- override fun unsubscribe(id: Long) = mainExecutor.execute { workerRequests.cancel(id) }
65
+ override fun subscribe(id: Long, plugin: String, method: String, payload: ByteArray) =
66
+ workerRequests.run(id, TokamakPluginRequest.SUBSCRIBE, plugin, method, payload)
67
+
68
+ override fun cancel(id: Long) = workerRequests.cancel(id)
64
69
 
65
- private fun parse(arguments: String): Any? = JSONTokener(arguments).nextValue()
66
70
  }
67
71
 
68
72
  /** The host of the app origin, `https://<appHost>`. */
@@ -75,6 +79,7 @@ class TokamakApplication : Application(), TokamakPlugins {
75
79
 
76
80
  override fun onCreate() {
77
81
  super.onCreate()
82
+ workerRequests = TokamakPluginRequests(plugins, pull = { id -> runtime.pull(id) }) { id, result -> runtime.reply(id, result) }
78
83
  ProcessLifecycleOwner.get().lifecycle.addObserver(
79
84
  object : DefaultLifecycleObserver {
80
85
  override fun onStart(owner: LifecycleOwner) = moved(foreground = true)
@@ -98,6 +103,9 @@ class TokamakApplication : Application(), TokamakPlugins {
98
103
  override val isInForeground: Boolean
99
104
  get() = this@TokamakApplication.isInForeground
100
105
 
106
+ override val resources: TokamakResources
107
+ get() = this@TokamakApplication.resources
108
+
101
109
  override fun requireForegroundActivity(): Activity =
102
110
  this@TokamakApplication.requireForegroundActivity()
103
111
 
@@ -109,8 +117,8 @@ class TokamakApplication : Application(), TokamakPlugins {
109
117
  callback: (Map<String, Boolean>) -> Unit,
110
118
  ) = permissionRequests.request(permissions, callback)
111
119
 
112
- override fun emit(name: String, event: String, timeoutMillis: Long): String =
113
- emitEvent("$id.$name", event, timeoutMillis)
120
+ override fun emitBytes(name: String, payload: ByteArray, timeoutMillis: Long): ByteArray =
121
+ emitEvent("$id.$name", payload, timeoutMillis)
114
122
 
115
123
  override fun fetch(path: String, timeoutMillis: Long): ByteArray {
116
124
  val deadline = SystemClock.elapsedRealtime() + timeoutMillis
@@ -131,13 +139,13 @@ class TokamakApplication : Application(), TokamakPlugins {
131
139
  get() = if (started.isInitialized()) runtime.isForeground else activity != null
132
140
 
133
141
  /**
134
- * Delivers the event [name] with the JSON [event] to the Worker's listeners and returns their
135
- * reply as JSON. Starts the runtime when it is not running. Blocks.
142
+ * Delivers the event [name] with its encoded [payload] to the Worker's listeners and returns
143
+ * their encoded reply. Starts the runtime when it is not running. Blocks.
136
144
  */
137
- private fun emitEvent(name: String, event: String, timeoutMillis: Long): String {
145
+ private fun emitEvent(name: String, payload: ByteArray, timeoutMillis: Long): ByteArray {
138
146
  val deadline = SystemClock.elapsedRealtime() + timeoutMillis
139
147
  val started = runtime
140
- return started.emit(name, event, deadline - SystemClock.elapsedRealtime())
148
+ return started.emit(name, payload, deadline - SystemClock.elapsedRealtime())
141
149
  }
142
150
 
143
151
  /** Records the app moving into or out of the foreground, once the runtime has started. */
@@ -150,7 +158,7 @@ class TokamakApplication : Application(), TokamakPlugins {
150
158
  if (!runtime.setForeground(foreground)) return
151
159
  val name = if (foreground) "resume" else "suspend"
152
160
  lifecycle.execute {
153
- runCatching { runtime.emit(name, "{}", LIFECYCLE_DEADLINE_MILLIS) }
161
+ runCatching { runtime.emit(name, "{}".toByteArray(), LIFECYCLE_DEADLINE_MILLIS) }
154
162
  .onFailure { Log.w("tokamak", "tokamak $name failed", it) }
155
163
  }
156
164
  }
@@ -0,0 +1,73 @@
1
+ package com.tokamak.runtime
2
+
3
+ import android.net.Uri
4
+ import java.net.URI
5
+ import java.util.concurrent.Executor
6
+ import java.util.concurrent.Executors
7
+ import org.json.JSONObject
8
+
9
+ /** Core device operations use the same endpoint and ownership as plugins. */
10
+ internal class TokamakCorePlugin(private val app: TokamakApplication) : TokamakPlugin {
11
+ override val id = "tokamak"
12
+ private val executor = Executors.newSingleThreadExecutor()
13
+
14
+ /** WebView operations and the activity run on the main thread, which WebView and activities require. */
15
+ override fun executor(method: String): Executor =
16
+ if (method.startsWith("webview.") || method == "resource.root") super.executor(method) else executor
17
+
18
+ override fun call(method: String, arguments: Any?, reply: TokamakPluginReply): (() -> Unit)? {
19
+ val view = (app.activity as? TokamakActivity)?.webView
20
+ when (method) {
21
+ "resource.read" -> reply(Result.success(app.resources.get(arguments, ByteArray::class.java)))
22
+ "resource.release" -> {
23
+ app.resources.release(arguments)
24
+ reply(Result.success(null))
25
+ }
26
+ "resource.root" -> reply(Result.success(root(arguments as JSONObject)))
27
+ "webview.getCurrentPage" -> reply(Result.success(view?.url))
28
+ "webview.navigate" -> {
29
+ if (view == null) throw noView()
30
+ val base = view.url?.let(::URI) ?: URI("https://${app.appHost}/")
31
+ val url = base.resolve(arguments as? String ?: throw notAppUrl())
32
+ if (!Uri.parse(url.toString()).isAppOrigin(app.appHost)) throw notAppUrl()
33
+ view.loadUrl(url.toString())
34
+ reply(Result.success(null))
35
+ }
36
+ "webview.postMessage" -> {
37
+ if (view?.url == null) throw TokamakPluginError("InvalidStateError", "No page is loaded")
38
+ val data = JSONObject().put("data", arguments ?: JSONObject.NULL).toString()
39
+ view.evaluateJavascript(
40
+ "(() => { const value = JSON.parse(${JSONObject.quote(data)});" +
41
+ "value.origin = location.origin; window.dispatchEvent(new MessageEvent('message', value)); return true; })()",
42
+ ) { result ->
43
+ if (result == "true") reply(Result.success(null))
44
+ else reply(Result.failure(TokamakPluginError("OperationError", "Page message delivery failed")))
45
+ }
46
+ }
47
+ else -> throw TokamakPluginError.notSupported("$id.$method is not supported")
48
+ }
49
+ return null
50
+ }
51
+
52
+ /** `resource.scope` opens a scope for the objects an invocation receives, which ends with the subscription. */
53
+ override fun subscribe(method: String, arguments: Any?, reply: TokamakPluginReply): () -> Unit {
54
+ if (method != "resource.scope") throw TokamakPluginError.notSupported("$id.$method is not supported")
55
+ val scope = app.resources.open()
56
+ reply(Result.success(scope))
57
+ return { app.resources.end(scope) }
58
+ }
59
+
60
+ /** Retains the app object [arguments] names in its scope and returns its ID: the application `context` or the foreground `activity`. */
61
+ private fun root(arguments: JSONObject): String {
62
+ val root: Any = when (arguments.getString("name")) {
63
+ "context" -> app
64
+ "activity" -> app.requireForegroundActivity()
65
+ else -> throw TokamakPluginError.notSupported("$id.resource.root has no such object")
66
+ }
67
+ return app.resources.retain(root, arguments.getString("scope"))
68
+ }
69
+
70
+ private fun noView() = TokamakPluginError("InvalidStateError", "The app has no WebView")
71
+
72
+ private fun notAppUrl() = TokamakPluginError.typeError("Navigation requires an app URL")
73
+ }
@@ -10,11 +10,17 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
10
10
  * per value for a subscription.
11
11
  */
12
12
  interface Plugins {
13
- fun call(id: Long, plugin: String, method: String, arguments: String)
13
+ fun call(id: Long, plugin: String, method: String, payload: ByteArray)
14
14
 
15
- fun subscribe(id: Long, plugin: String, method: String, arguments: String)
15
+ /** A call with a body, whose chunks the shell asks for with [pull] and receives in [chunk]. */
16
+ fun callWithBody(id: Long, plugin: String, method: String, payload: ByteArray)
16
17
 
17
- fun unsubscribe(id: Long)
18
+ /** The chunk of the call [id]'s body the shell pulled: bytes, or an encoded error when [failed]. */
19
+ fun chunk(id: Long, payload: ByteArray, failed: Boolean, done: Boolean)
20
+
21
+ fun subscribe(id: Long, plugin: String, method: String, payload: ByteArray)
22
+
23
+ fun cancel(id: Long)
18
24
  }
19
25
 
20
26
  /** The loopback port the gateway bound. */
@@ -24,11 +30,12 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
24
30
  fun restoreGateway(): Int = nativeRestoreGateway(handle)
25
31
 
26
32
  /**
27
- * Delivers the event [name] with the JSON [event] to the Worker's listeners, blocking until
28
- * they return or [timeoutMillis] passes, and returns their reply as JSON.
33
+ * Delivers the event [name] with its encoded [payload] to the Worker's listeners, blocking
34
+ * until they return or [timeoutMillis] passes, and returns their encoded reply, which is empty
35
+ * when none replied.
29
36
  */
30
- fun emit(name: String, event: String, timeoutMillis: Long): String =
31
- nativeEmit(handle, name, event, timeoutMillis)
37
+ fun emit(name: String, payload: ByteArray, timeoutMillis: Long): ByteArray =
38
+ nativeEmit(handle, name, payload, timeoutMillis)
32
39
 
33
40
  /** What the app serves at [path], blocking until it arrives or [timeoutMillis] passes. */
34
41
  fun fetch(path: String, timeoutMillis: Long): ByteArray = nativeFetch(handle, path, timeoutMillis)
@@ -43,8 +50,12 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
43
50
  val isForeground: Boolean
44
51
  get() = nativeIsForeground(handle)
45
52
 
46
- /** Passes a plugin's JSON [result] to the Worker's call or subscription [id]. */
47
- fun reply(id: Long, result: String) = nativeReply(handle, id, result)
53
+ /** Asks the Worker for the next chunk of the body of the call [id]. */
54
+ fun pull(id: Long) = nativePull(handle, id)
55
+
56
+ /** Passes an encoded plugin result to its native invocation. */
57
+ fun reply(id: Long, result: TokamakPluginResult) =
58
+ nativeReply(handle, id, result.payload, result.failed, result.done)
48
59
 
49
60
  /**
50
61
  * The authority a server certificate for [host] must chain to, or null
@@ -123,7 +134,10 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
123
134
  private external fun nativeIsForeground(handle: Long): Boolean
124
135
 
125
136
  @JvmStatic
126
- private external fun nativeReply(handle: Long, id: Long, result: String)
137
+ private external fun nativeReply(handle: Long, id: Long, payload: ByteArray, failed: Boolean, done: Boolean)
138
+
139
+ @JvmStatic
140
+ private external fun nativePull(handle: Long, id: Long)
127
141
 
128
142
  @JvmStatic
129
143
  private external fun nativePort(handle: Long): Int
@@ -135,9 +149,9 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
135
149
  private external fun nativeEmit(
136
150
  handle: Long,
137
151
  name: String,
138
- event: String,
152
+ event: ByteArray,
139
153
  timeoutMillis: Long,
140
- ): String
154
+ ): ByteArray
141
155
 
142
156
  @JvmStatic
143
157
  private external fun nativeFetch(handle: Long, path: String, timeoutMillis: Long): ByteArray
@@ -22,10 +22,8 @@ internal class TokamakWebViewClient(
22
22
  private val activity: Activity,
23
23
  private val host: String,
24
24
  private val runtime: TokamakRuntime,
25
- private val pluginBridge: TokamakPluginBridge,
26
25
  ) : WebViewClient() {
27
26
  override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
28
- pluginBridge.close()
29
27
  val uri = Uri.parse(url)
30
28
  if (!uri.isAppOrigin(host)) {
31
29
  view.stopLoading()
@@ -0,0 +1,181 @@
1
+ package com.tokamak.runtime
2
+
3
+ import java.util.Base64
4
+ import org.json.JSONArray
5
+ import org.json.JSONObject
6
+
7
+ /**
8
+ * One call or subscription of a generated platform binding. It decodes the Worker's JSON into
9
+ * native values and encodes native values back, keeping the native objects it returns in the
10
+ * receiving invocation's scope.
11
+ *
12
+ * JSON objects tagged `#` carry what JSON lacks: native objects, bytes, errors, non-finite
13
+ * numbers, and records whose keys include `#`.
14
+ */
15
+ class TokamakBinding(payload: ByteArray, private val resources: TokamakResources, private val reply: TokamakPluginBytesReply) {
16
+ companion object {
17
+ /** The rejection of a member the running API level lacks. */
18
+ val unavailable get() = TokamakPluginError.notSupported("The API is unavailable on this API level")
19
+ }
20
+
21
+ private val request = runCatching {
22
+ decodePluginValue(payload) as? JSONObject ?: throw TokamakPluginError.typeError("A binding request is an object")
23
+ }
24
+
25
+ /** Argument [index] as JSON. */
26
+ operator fun get(index: Int): Any? = request.getOrThrow().optJSONArray("arguments")?.opt(index) ?: JSONObject.NULL
27
+
28
+ /** The object the call is made on. */
29
+ fun <T : Any> target(type: Class<T>): T = obj(request.getOrThrow().opt("target"), type)
30
+
31
+ /** The handlers an implementation calls. */
32
+ val methods: Set<String>
33
+ get() {
34
+ val methods = request.getOrNull()?.optJSONArray("methods") ?: return emptySet()
35
+ return (0 until methods.length()).map(methods::getString).toSet()
36
+ }
37
+
38
+ private val scope: String
39
+ get() = request.getOrNull()?.optString("scope").orEmpty()
40
+
41
+ fun boolean(value: Any?): Boolean = value as? Boolean ?: throw mismatch(value, "boolean")
42
+
43
+ fun byte(value: Any?): Byte = long(value).let { if (it in Byte.MIN_VALUE..Byte.MAX_VALUE) it.toByte() else throw mismatch(value, "byte") }
44
+
45
+ fun short(value: Any?): Short = long(value).let { if (it in Short.MIN_VALUE..Short.MAX_VALUE) it.toShort() else throw mismatch(value, "short") }
46
+
47
+ fun int(value: Any?): Int = long(value).let { if (it in Int.MIN_VALUE..Int.MAX_VALUE) it.toInt() else throw mismatch(value, "int") }
48
+
49
+ fun long(value: Any?): Long {
50
+ val number = double(value)
51
+ val integer = number.toLong()
52
+ if (integer.toDouble() != number) throw mismatch(value, "long")
53
+ return integer
54
+ }
55
+
56
+ fun float(value: Any?): Float = double(value).toFloat()
57
+
58
+ fun double(value: Any?): Double =
59
+ (value as? Number)?.toDouble() ?: string(tagged(value, "number")).toDoubleOrNull() ?: throw mismatch(value, "double")
60
+
61
+ fun char(value: Any?): Char = string(value).singleOrNull() ?: throw mismatch(value, "char")
62
+
63
+ fun string(value: Any?): String = value as? String ?: throw mismatch(value, "String")
64
+
65
+ fun bytes(value: Any?): ByteArray = Base64.getDecoder().decode(string(tagged(value, "bytes")))
66
+
67
+ /** The native object [value] refers to. */
68
+ fun <T : Any> obj(value: Any?, type: Class<T>): T = resources.get(tagged(value, "object", "id"), type)
69
+
70
+ /** A value of an erased or `Object` type: JSON as it is, or the native value a tag carries. */
71
+ fun any(value: Any?): Any? =
72
+ when (value) {
73
+ null, JSONObject.NULL -> null
74
+ is JSONArray -> list(value, ::any)
75
+ is JSONObject ->
76
+ when (value.optString("#")) {
77
+ "object" -> obj(value, Any::class.java)
78
+ "bytes" -> bytes(value)
79
+ "number" -> double(value)
80
+ else -> map(value, ::any)
81
+ }
82
+ else -> value
83
+ }
84
+
85
+ fun <T> optional(value: Any?, decode: (Any?) -> T): T? = if (value == null || value == JSONObject.NULL) null else decode(value)
86
+
87
+ fun <T> list(value: Any?, decode: (Any?) -> T): List<T> {
88
+ val values = value as? JSONArray ?: throw mismatch(value, "List")
89
+ return (0 until values.length()).map { decode(values.get(it)) }
90
+ }
91
+
92
+ fun <T> map(value: Any?, decode: (Any?) -> T): Map<String, T> {
93
+ val fields = (value as? JSONObject)?.let { if (it.optString("#") == "record") it.getJSONObject("value") else it }
94
+ ?: throw mismatch(value, "Map")
95
+ return fields.keys().asSequence().associateWith { decode(fields.get(it)) }
96
+ }
97
+
98
+ /**
99
+ * [value] as JSON: values by their runtime type, and native objects as references kept in the
100
+ * invocation's scope, with the names of their class and superclasses.
101
+ */
102
+ fun encode(value: Any?): Any =
103
+ when (value) {
104
+ null -> JSONObject.NULL
105
+ is Boolean, is String, is Int, is Long, is Short, is Byte -> value
106
+ is Double -> if (value.isFinite()) value else JSONObject().put("#", "number").put("value", value.toString())
107
+ is Float -> encode(value.toDouble())
108
+ is Char, is CharSequence -> value.toString()
109
+ is ByteArray -> JSONObject().put("#", "bytes").put("value", Base64.getEncoder().encodeToString(value))
110
+ is IntArray -> JSONArray(value.map(::encode))
111
+ is LongArray -> JSONArray(value.map(::encode))
112
+ is FloatArray -> JSONArray(value.map(::encode))
113
+ is DoubleArray -> JSONArray(value.map(::encode))
114
+ is BooleanArray -> JSONArray(value.map(::encode))
115
+ is Array<*> -> JSONArray(value.map(::encode))
116
+ is Iterable<*> -> JSONArray(value.map(::encode))
117
+ is Map<*, *> -> record(value)
118
+ is Enum<*> -> value.name
119
+ is Throwable -> error(value)
120
+ else -> JSONObject().put("#", "object").put("id", resources.retain(value, scope)).put("types", JSONArray(types(value)))
121
+ }
122
+
123
+ /** Replies with the JSON [body] returns, or the exception it throws. */
124
+ fun run(body: () -> Any?): (() -> Unit)? {
125
+ reply(TokamakPluginResult.encoded(runCatching { encodePluginValue(body()) }, true))
126
+ return null
127
+ }
128
+
129
+ /** Keeps the implementation [create] makes while the subscription lasts, and replies with its ID. */
130
+ fun implement(create: (TokamakBinding) -> Any): () -> Unit {
131
+ val scope = resources.open()
132
+ send(resources.retain(create(this), scope))
133
+ return { resources.end(scope) }
134
+ }
135
+
136
+ /**
137
+ * Calls the handler [method], when the implementation has one, with the arguments it encodes,
138
+ * and returns whether it had one.
139
+ */
140
+ fun call(method: String, arguments: (TokamakBinding) -> List<Any?>): Boolean {
141
+ if (method !in methods) return false
142
+ send(JSONObject().put("method", method).put("arguments", JSONArray(arguments(this))))
143
+ return true
144
+ }
145
+
146
+ /** Rejects the member the plugin does not bind. */
147
+ fun unsupported(member: String): (() -> Unit)? {
148
+ reply(TokamakPluginResult.encoded(Result.failure(TokamakPluginError.notSupported("$member is not supported")), true))
149
+ return null
150
+ }
151
+
152
+ private fun send(value: Any?) {
153
+ reply(TokamakPluginResult.encoded(runCatching { encodePluginValue(value) }, false))
154
+ }
155
+
156
+ private fun record(fields: Map<*, *>): JSONObject {
157
+ val encoded = JSONObject()
158
+ fields.forEach { (key, value) -> encoded.put(key.toString(), encode(value)) }
159
+ return if (encoded.has("#")) JSONObject().put("#", "record").put("value", encoded) else encoded
160
+ }
161
+
162
+ private fun error(error: Throwable): JSONObject = failure(error).put("#", "error")
163
+
164
+ /** The field [key] of [value] tagged [tag]. */
165
+ private fun tagged(value: Any?, tag: String, key: String = "value"): Any? {
166
+ val fields = value as? JSONObject
167
+ if (fields?.optString("#") != tag || !fields.has(key)) throw TokamakPluginError.typeError("Expected a tagged $tag")
168
+ return fields.get(key)
169
+ }
170
+
171
+ private fun mismatch(value: Any?, type: String) = TokamakPluginError.typeError("${value?.javaClass?.simpleName} is not $type")
172
+
173
+ /** The names of [value]'s class and superclasses, then of the interfaces they implement. */
174
+ private fun types(value: Any): List<String> {
175
+ val classes = generateSequence<Class<*>>(value.javaClass) { it.superclass }.toList()
176
+ return (classes + classes.flatMap(::interfaces)).distinct().map { it.name }
177
+ }
178
+
179
+ /** The interfaces [type] implements, each followed by those it extends. */
180
+ private fun interfaces(type: Class<*>): List<Class<*>> = type.interfaces.flatMap { listOf(it) + interfaces(it) }
181
+ }
@@ -29,8 +29,10 @@ fun TokamakHost.authenticateOwner(
29
29
  authenticators: Int,
30
30
  crypto: BiometricPrompt.CryptoObject?,
31
31
  reply: TokamakPluginReply,
32
+ cancellation: CancellationSignal = CancellationSignal(),
32
33
  succeeded: () -> Unit,
33
- ) {
34
+ ): () -> Unit {
35
+ cancellation.throwIfCanceled()
34
36
  val activity = requireForegroundActivity()
35
37
  val builder = BiometricPrompt.Builder(activity).setTitle(title).setAllowedAuthenticators(authenticators)
36
38
  if ((authenticators and Authenticators.DEVICE_CREDENTIAL) == 0) {
@@ -41,10 +43,11 @@ fun TokamakHost.authenticateOwner(
41
43
  val prompt = builder.build()
42
44
  val callback = PromptCallback(reply, succeeded)
43
45
  if (crypto == null) {
44
- prompt.authenticate(CancellationSignal(), activity.mainExecutor, callback)
46
+ prompt.authenticate(cancellation, activity.mainExecutor, callback)
45
47
  } else {
46
- prompt.authenticate(crypto, CancellationSignal(), activity.mainExecutor, callback)
48
+ prompt.authenticate(crypto, cancellation, activity.mainExecutor, callback)
47
49
  }
50
+ return { cancellation.cancel() }
48
51
  }
49
52
 
50
53
  private class PromptCallback(
@@ -3,14 +3,22 @@ package com.tokamak.runtime
3
3
  import android.app.Activity
4
4
  import android.content.Context
5
5
  import android.content.Intent
6
+ import android.os.Handler
7
+ import android.os.Looper
8
+ import java.util.concurrent.Executor
9
+ import org.json.JSONArray
10
+ import org.json.JSONObject
11
+ import org.json.JSONTokener
6
12
 
7
13
  /**
8
- * A failure a plugin reports to the page as a `DOMException` named [errorName]. Other exceptions
9
- * reach the page as an `OperationError`.
14
+ * A failure a plugin reports to the worker as a `DOMException` named [errorName]. Other exceptions
15
+ * reach the worker as an `OperationError`.
10
16
  */
11
17
  class TokamakPluginError(
12
18
  val errorName: String,
13
19
  message: String,
20
+ /** JSON details the Worker receives as the error's `cause`. */
21
+ val errorCause: Any? = null,
14
22
  ) : Exception(message) {
15
23
  companion object {
16
24
  fun notSupported(message: String) = TokamakPluginError("NotSupportedError", message)
@@ -23,6 +31,85 @@ class TokamakPluginError(
23
31
  }
24
32
 
25
33
  typealias TokamakPluginReply = (Result<Any?>) -> Unit
34
+ typealias TokamakPluginBytesReply = (TokamakPluginResult) -> Unit
35
+
36
+ data class TokamakPluginResult(val payload: ByteArray, val failed: Boolean, val done: Boolean) {
37
+ companion object {
38
+ fun encoded(result: Result<ByteArray>, done: Boolean): TokamakPluginResult {
39
+ val error = result.exceptionOrNull()
40
+ ?: return TokamakPluginResult(result.getOrThrow(), false, done)
41
+ return TokamakPluginResult(failure(error).toString().toByteArray(Charsets.UTF_8), true, done)
42
+ }
43
+ }
44
+ }
45
+
46
+ /** [error] for the Worker: its name, message and cause, or an `OperationError` caused by the exception's class. */
47
+ internal fun failure(error: Throwable): JSONObject {
48
+ val failure = JSONObject().put("message", error.message ?: error.javaClass.name)
49
+ return if (error is TokamakPluginError) {
50
+ failure.put("name", error.errorName).putOpt("cause", JSONObject.wrap(error.errorCause))
51
+ } else {
52
+ failure.put("name", "OperationError").put("cause", JSONObject().put("exception", error.javaClass.name))
53
+ }
54
+ }
55
+
56
+ internal fun decodePluginValue(payload: ByteArray): Any? = JSONTokener(payload.toString(Charsets.UTF_8)).nextValue()
57
+
58
+ /**
59
+ * The bytes the Worker streams to a call, which the plugin reads one chunk at a time on the call's
60
+ * [executor]; [pull] asks the Worker for the next.
61
+ */
62
+ class TokamakPluginBody internal constructor(private val executor: Executor, private val pull: () -> Unit) {
63
+ private var reading: ((Result<ByteArray?>) -> Unit)? = null
64
+
65
+ /**
66
+ * Reads the next chunk: its bytes, null after the last, or the Worker's error. [handler] runs on
67
+ * the call's executor; read again only after it has.
68
+ */
69
+ fun read(handler: (Result<ByteArray?>) -> Unit) {
70
+ synchronized(this) { reading = handler }
71
+ pull()
72
+ }
73
+
74
+ /** Answers the pending read with the chunk the Worker sent. */
75
+ internal fun receive(chunk: TokamakPluginResult) {
76
+ val handler = synchronized(this) { reading.also { reading = null } } ?: return
77
+ executor.execute {
78
+ handler(
79
+ when {
80
+ chunk.failed -> Result.failure(chunkError(chunk.payload))
81
+ chunk.done -> Result.success(null)
82
+ else -> Result.success(chunk.payload)
83
+ },
84
+ )
85
+ }
86
+ }
87
+
88
+ private fun chunkError(payload: ByteArray): TokamakPluginError {
89
+ val error = runCatching { JSONObject(payload.toString(Charsets.UTF_8)) }.getOrNull()
90
+ return TokamakPluginError(error?.optString("name", "Error") ?: "Error", error?.optString("message", "") ?: "")
91
+ }
92
+ }
93
+
94
+ /** [value] as a payload: a [ByteArray] as it is, and any other value as JSON. */
95
+ internal fun encodePluginValue(value: Any?): ByteArray {
96
+ if (value is ByteArray) return value
97
+ val wrapped = JSONObject.wrap(value)
98
+ if (value != null && wrapped == null) throw TokamakPluginError("DataCloneError", "The plugin value cannot be encoded as JSON")
99
+ val json = when (wrapped) {
100
+ null, JSONObject.NULL -> "null"
101
+ is String -> JSONObject.quote(wrapped)
102
+ is Number -> JSONObject.numberToString(wrapped)
103
+ is Boolean, is JSONObject, is JSONArray -> wrapped.toString()
104
+ else -> throw TokamakPluginError("DataCloneError", "The plugin value cannot be encoded as JSON")
105
+ }
106
+ return json.toByteArray(Charsets.UTF_8)
107
+ }
108
+
109
+ private val uiExecutor by lazy {
110
+ val main = Handler(Looper.getMainLooper())
111
+ Executor { main.post(it) }
112
+ }
26
113
 
27
114
  /**
28
115
  * A native plugin, created once per process with the app's [TokamakHost]. A [call] or [subscribe]
@@ -31,8 +118,37 @@ typealias TokamakPluginReply = (Result<Any?>) -> Unit
31
118
  interface TokamakPlugin {
32
119
  val id: String
33
120
 
34
- fun call(method: String, arguments: Any?, reply: TokamakPluginReply) {
121
+ /** Serial executor for this operation and its cancellation. */
122
+ fun executor(method: String): Executor = uiExecutor
123
+
124
+ fun callBytes(method: String, payload: ByteArray, reply: TokamakPluginBytesReply): (() -> Unit)? =
125
+ call(method, decodePluginValue(payload)) { reply(TokamakPluginResult.encoded(it.mapCatching(::encodePluginValue), true)) }
126
+
127
+ fun callBytes(
128
+ method: String,
129
+ payload: ByteArray,
130
+ body: TokamakPluginBody,
131
+ reply: TokamakPluginBytesReply,
132
+ ): (() -> Unit)? =
133
+ call(method, decodePluginValue(payload), body) {
134
+ reply(TokamakPluginResult.encoded(it.mapCatching(::encodePluginValue), true))
135
+ }
136
+
137
+ fun subscribeBytes(method: String, payload: ByteArray, reply: TokamakPluginBytesReply): () -> Unit =
138
+ subscribe(method, decodePluginValue(payload)) {
139
+ reply(TokamakPluginResult.encoded(it.mapCatching(::encodePluginValue), false))
140
+ }
141
+
142
+ /** Returns cancellation for pending work when the platform supports it. */
143
+ fun call(method: String, arguments: Any?, reply: TokamakPluginReply): (() -> Unit)? {
35
144
  reply(Result.failure(TokamakPluginError.notSupported("$id.$method is not supported")))
145
+ return null
146
+ }
147
+
148
+ /** A call whose [body] of bytes the Worker streams, which the plugin reads one chunk at a time. */
149
+ fun call(method: String, arguments: Any?, body: TokamakPluginBody, reply: TokamakPluginReply): (() -> Unit)? {
150
+ reply(Result.failure(TokamakPluginError.notSupported("$id.$method does not take a body")))
151
+ return null
36
152
  }
37
153
 
38
154
  fun subscribe(
@@ -40,8 +156,7 @@ interface TokamakPlugin {
40
156
  arguments: Any?,
41
157
  reply: TokamakPluginReply,
42
158
  ): () -> Unit {
43
- reply(Result.failure(TokamakPluginError.notSupported("$id.$method is not supported")))
44
- return {}
159
+ throw TokamakPluginError.notSupported("$id.$method is not supported")
45
160
  }
46
161
 
47
162
  /** Receives the intent that started the app's activity, and each intent it receives later. */
@@ -59,6 +174,9 @@ interface TokamakHost {
59
174
  /** Whether the app is in the foreground, where it can show UI. Read it on the main thread. */
60
175
  val isInForeground: Boolean
61
176
 
177
+ /** The native objects plugins share with each other by ID. */
178
+ val resources: TokamakResources
179
+
62
180
  /**
63
181
  * The activity to show UI in. Throws `NeedsUIError` while the app is in the background, where
64
182
  * it cannot show UI. Call it on the main thread.
@@ -81,11 +199,16 @@ interface TokamakHost {
81
199
 
82
200
  /**
83
201
  * Delivers the plugin's event [name], which the Worker's listeners receive as
84
- * `<plugin>.<name>`, with the JSON [event], and returns their reply as JSON, `null` when none
85
- * replies. Starts the runtime when it is not running. Blocks, so call it off the main thread;
86
- * throws unless the listeners return within [timeoutMillis], which includes runtime startup.
202
+ * `<plugin>.<name>`, with its encoded [payload], and returns their encoded reply, which is
203
+ * empty when none replied. Starts the runtime when it is not running. Blocks, so call it off
204
+ * the main thread; throws unless the listeners return within [timeoutMillis], which includes
205
+ * runtime startup.
87
206
  */
88
- fun emit(name: String, event: String, timeoutMillis: Long): String
207
+ fun emitBytes(name: String, payload: ByteArray, timeoutMillis: Long): ByteArray
208
+
209
+ /** [emitBytes] with the JSON [event], returning their reply as JSON, `null` when none replied. */
210
+ fun emit(name: String, event: String, timeoutMillis: Long): String =
211
+ emitBytes(name, event.toByteArray(Charsets.UTF_8), timeoutMillis).toString(Charsets.UTF_8).ifEmpty { "null" }
89
212
 
90
213
  /**
91
214
  * What the app serves at [path], as its WebView would load it: a file the app ships or the
@@ -0,0 +1,87 @@
1
+ package com.tokamak.runtime
2
+
3
+ import java.util.concurrent.Executor
4
+
5
+ /** What the Worker asked a plugin for. */
6
+ enum class TokamakPluginRequest { CALL, CALL_WITH_BODY, SUBSCRIBE }
7
+
8
+ /**
9
+ * Runs the Worker's requests on the executor each plugin chooses, and passes replies straight to the
10
+ * runtime with [send]; [pull] asks the Worker for the next chunk of a call's body.
11
+ */
12
+ class TokamakPluginRequests<K>(
13
+ private val plugins: Map<String, TokamakPlugin>,
14
+ private val pull: (K) -> Unit = {},
15
+ private val send: (K, TokamakPluginResult) -> Unit,
16
+ ) {
17
+ /** A pending call or subscription. Only its serial executor touches [cancellation], so a cancellation runs after the operation started. */
18
+ private class Request(val executor: Executor) {
19
+ var body: TokamakPluginBody? = null
20
+ var cancellation: (() -> Unit)? = null
21
+ }
22
+
23
+ private val pending = mutableMapOf<K, Request>()
24
+
25
+ fun run(key: K, kind: TokamakPluginRequest, plugin: String, method: String, payload: ByteArray) {
26
+ val target = plugins[plugin]
27
+ if (target == null || method.isEmpty()) {
28
+ send(key, failure(TokamakPluginError.notSupported("Plugin is not supported")))
29
+ return
30
+ }
31
+ val request = Request(target.executor(method))
32
+ if (kind == TokamakPluginRequest.CALL_WITH_BODY) request.body = TokamakPluginBody(request.executor) { pull(key) }
33
+ synchronized(pending) { pending[key] = request }
34
+ val subscribe = kind == TokamakPluginRequest.SUBSCRIBE
35
+ val reply: TokamakPluginBytesReply = { result ->
36
+ val last = !subscribe || result.done
37
+ if (if (last) remove(key, request) else isPending(key, request)) {
38
+ send(key, result)
39
+ if (subscribe && result.done) cancel(request)
40
+ }
41
+ }
42
+ request.executor.execute {
43
+ if (!isPending(key, request)) return@execute
44
+ try {
45
+ val body = request.body
46
+ request.cancellation = when {
47
+ subscribe -> target.subscribeBytes(method, payload, reply)
48
+ body != null -> target.callBytes(method, payload, body, reply)
49
+ else -> target.callBytes(method, payload, reply)
50
+ }
51
+ } catch (error: Exception) {
52
+ if (remove(key, request)) send(key, failure(error))
53
+ }
54
+ }
55
+ }
56
+
57
+ /** Answers the pending read of the call [key]'s body with the chunk the Worker sent. */
58
+ fun chunk(key: K, chunk: TokamakPluginResult) {
59
+ synchronized(pending) { pending[key]?.body }?.receive(chunk)
60
+ }
61
+
62
+ fun cancel(key: K) {
63
+ synchronized(pending) { pending.remove(key) }?.let(::cancel)
64
+ }
65
+
66
+ fun cancelAll() {
67
+ val requests = synchronized(pending) { pending.values.toList().also { pending.clear() } }
68
+ requests.forEach(::cancel)
69
+ }
70
+
71
+ /** Runs the operation's cancellation on its executor. */
72
+ private fun cancel(request: Request) {
73
+ request.executor.execute {
74
+ request.cancellation?.invoke()
75
+ request.cancellation = null
76
+ }
77
+ }
78
+
79
+ private fun isPending(key: K, request: Request) = synchronized(pending) { pending[key] === request }
80
+
81
+ /** Removes [request], returning whether it was pending. */
82
+ private fun remove(key: K, request: Request) = synchronized(pending) {
83
+ (pending[key] === request).also { if (it) pending.remove(key) }
84
+ }
85
+
86
+ private fun failure(error: Throwable) = TokamakPluginResult.encoded(Result.failure(error), done = true)
87
+ }
@@ -0,0 +1,53 @@
1
+ package com.tokamak.runtime
2
+
3
+ import java.util.UUID
4
+
5
+ /** Native objects that plugins share by ID. Each belongs to a scope and is kept until it is released or its scope ends. */
6
+ class TokamakResources {
7
+ private val objects = HashMap<String, Pair<Any, String>>()
8
+ private val scopes = HashMap<String, MutableSet<String>>()
9
+
10
+ /** Starts a scope and returns its ID. */
11
+ fun open(): String {
12
+ val scope = UUID.randomUUID().toString()
13
+ synchronized(this) { scopes[scope] = HashSet() }
14
+ return scope
15
+ }
16
+
17
+ /** Keeps [value] in [scope] and returns its ID. An ended scope keeps nothing, so the ID finds no object. */
18
+ fun retain(value: Any, scope: String): String {
19
+ val id = UUID.randomUUID().toString()
20
+ synchronized(this) {
21
+ if (scopes[scope]?.add(id) == true) objects[id] = value to scope
22
+ }
23
+ return id
24
+ }
25
+
26
+ /** Keeps [value] in a scope of its own, replies with its ID, and returns the release to return from `subscribe`. */
27
+ fun retain(value: Any, reply: TokamakPluginReply): () -> Unit {
28
+ val scope = open()
29
+ reply(Result.success(retain(value, scope)))
30
+ return { end(scope) }
31
+ }
32
+
33
+ /** Releases the object retained as [id], if it is still kept. */
34
+ fun release(id: Any?) {
35
+ synchronized(this) {
36
+ val (_, scope) = objects.remove(id as? String) ?: return
37
+ scopes[scope]?.remove(id)
38
+ }
39
+ }
40
+
41
+ /** Releases every object [scope] keeps, and keeps nothing in it later. */
42
+ fun end(scope: String) {
43
+ synchronized(this) { scopes.remove(scope)?.forEach { objects.remove(it) } }
44
+ }
45
+
46
+ /** The object retained as [id]. */
47
+ fun <T : Any> get(id: Any?, type: Class<T>): T {
48
+ val value = synchronized(this) { objects[id as? String]?.first }
49
+ ?: throw TokamakPluginError("InvalidStateError", "The native reference is closed")
50
+ if (!type.isInstance(value)) throw TokamakPluginError.typeError("The native reference is not ${type.simpleName}")
51
+ return type.cast(value)!!
52
+ }
53
+ }
@@ -24,6 +24,7 @@
24
24
  }
25
25
  },
26
26
  "pluginKeys": {
27
+ "bindings": "paths",
27
28
  "class": "string",
28
29
  "dependencies": "strings",
29
30
  "manifest": "path",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokamakdev/platform-android-arm64",
3
- "version": "0.1.1-beta.106",
3
+ "version": "0.1.1-beta.112",
4
4
  "description": "The tokamak platform pack for android-arm64",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,79 +0,0 @@
1
- package com.tokamak.runtime
2
-
3
- import android.app.Activity
4
- import android.net.Uri
5
- import android.webkit.WebView
6
- import androidx.webkit.JavaScriptReplyProxy
7
- import androidx.webkit.WebMessageCompat
8
- import androidx.webkit.WebViewCompat
9
- import org.json.JSONObject
10
-
11
- /** Carries calls and subscriptions between the page and the app's plugins. */
12
- internal class TokamakPluginBridge(
13
- private val activity: Activity,
14
- private val host: String,
15
- plugins: Map<String, TokamakPlugin>,
16
- ) : WebViewCompat.WebMessageListener {
17
- private data class RequestKey(val session: String, val id: Int)
18
-
19
- private val requests = TokamakPluginRequests<RequestKey>(plugins, ::send)
20
- private var activeSession: String? = null
21
- private var replyProxy: JavaScriptReplyProxy? = null
22
-
23
- fun install(webView: WebView) {
24
- WebViewCompat.addWebMessageListener(
25
- webView,
26
- "__tokamakNative",
27
- setOf("https://$host"),
28
- this,
29
- )
30
- }
31
-
32
- fun close() {
33
- activeSession = null
34
- replyProxy = null
35
- requests.cancelAll()
36
- }
37
-
38
- override fun onPostMessage(
39
- view: WebView,
40
- message: WebMessageCompat,
41
- sourceOrigin: Uri,
42
- isMainFrame: Boolean,
43
- replyProxy: JavaScriptReplyProxy,
44
- ) {
45
- if (!isMainFrame || !sourceOrigin.isAppOrigin(host)) return
46
- val request = runCatching { JSONObject(message.data ?: return) }.getOrNull() ?: return
47
- val session = request.optString("session")
48
- if (session.isEmpty()) return
49
- val type = request.optString("type")
50
- if (type == "reset") {
51
- close()
52
- activeSession = session
53
- this.replyProxy = replyProxy
54
- return
55
- }
56
- val id = request.optInt("id", -1)
57
- if (id < 0) return
58
- val key = RequestKey(session, id)
59
- when (type) {
60
- "cancel" -> requests.cancel(key)
61
- "call", "subscribe" ->
62
- requests.run(
63
- key,
64
- type == "subscribe",
65
- request.optString("plugin"),
66
- request.optString("method"),
67
- request.opt("arguments"),
68
- )
69
- else -> requests.fail(key, TokamakPluginError.notSupported("Plugin operation is not supported"))
70
- }
71
- }
72
-
73
- /** Passes [result] to the page that made the request [key], if it is still loaded. */
74
- private fun send(key: RequestKey, result: JSONObject) =
75
- activity.runOnUiThread {
76
- if (activeSession != key.session) return@runOnUiThread
77
- replyProxy?.postMessage(result.put("session", key.session).put("id", key.id).toString())
78
- }
79
- }
@@ -1,57 +0,0 @@
1
- package com.tokamak.runtime
2
-
3
- import org.json.JSONObject
4
-
5
- /**
6
- * Runs one caller's calls and subscriptions, the page's or the Worker's, on the app's plugins,
7
- * keyed by [K]. [send] receives each result, on the thread the plugin replies on, as the JSON
8
- * object the page's native transport receives without its session and ID. Use it on the main
9
- * thread.
10
- */
11
- internal class TokamakPluginRequests<K>(
12
- private val plugins: Map<String, TokamakPlugin>,
13
- private val send: (K, JSONObject) -> Unit,
14
- ) {
15
- private val cancellations = mutableMapOf<K, () -> Unit>()
16
-
17
- /** Calls [method] of [plugin], or subscribes to it when [subscribe]. */
18
- fun run(key: K, subscribe: Boolean, plugin: String, method: String, arguments: Any?) {
19
- val target = plugins[plugin]
20
- if (target == null || method.isEmpty()) {
21
- fail(key, TokamakPluginError.notSupported("Plugin is not supported"))
22
- return
23
- }
24
- val reply: TokamakPluginReply = { result -> send(key, result(result, done = !subscribe)) }
25
- try {
26
- if (subscribe) {
27
- cancellations[key] = target.subscribe(method, arguments, reply)
28
- } else {
29
- target.call(method, arguments, reply)
30
- }
31
- } catch (error: Exception) {
32
- fail(key, error)
33
- }
34
- }
35
-
36
- /** Ends the request [key] with [error]. */
37
- fun fail(key: K, error: Throwable) = send(key, result(Result.failure(error), done = true))
38
-
39
- /** Ends the subscription [key]. */
40
- fun cancel(key: K) {
41
- cancellations.remove(key)?.invoke()
42
- }
43
-
44
- /** Ends every subscription. */
45
- fun cancelAll() {
46
- val cancelAll = cancellations.values.toList()
47
- cancellations.clear()
48
- cancelAll.forEach { it() }
49
- }
50
-
51
- private fun result(result: Result<Any?>, done: Boolean): JSONObject {
52
- val json = JSONObject().put("done", done)
53
- val error = result.exceptionOrNull() ?: return json.put("value", JSONObject.wrap(result.getOrNull()))
54
- val name = (error as? TokamakPluginError)?.errorName ?: "OperationError"
55
- return json.put("error", JSONObject().put("name", name).put("message", error.message ?: error.javaClass.name))
56
- }
57
- }