@tokamakdev/platform-android-arm64 0.1.1-beta.82 → 0.1.1-beta.84
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/android-arm64/build/entrypoint +10 -4
- package/android-arm64/lib/TokamakRuntime/libtokamak.a +2 -2
- package/android-arm64/native-shell/app/TokamakApplication.kt +119 -16
- package/android-arm64/native-shell/app/TokamakPermissions.kt +34 -5
- package/android-arm64/native-shell/app/TokamakPluginBridge.kt +21 -70
- package/android-arm64/native-shell/app/TokamakPluginRequests.kt +57 -0
- package/android-arm64/native-shell/app/TokamakRuntime.kt +57 -11
- package/android-arm64/native-shell/app/TokamakWebChromeClient.kt +8 -3
- package/android-arm64/native-shell/plugin/TokamakOwnerAuthentication.kt +3 -6
- package/android-arm64/native-shell/plugin/TokamakPlugin.kt +31 -10
- package/package.json +1 -1
|
@@ -176,7 +176,7 @@ fi
|
|
|
176
176
|
kotlin_class='^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)+$'
|
|
177
177
|
maven_coordinate='^[A-Za-z0-9._-]+:[A-Za-z0-9._-]+:[A-Za-z0-9._-]+$'
|
|
178
178
|
registry=$kotlin/TokamakPluginRegistry.kt
|
|
179
|
-
printf '%s\n\n%s\n%s\n' 'package com.tokamak.runtime' 'internal fun tokamakPlugins(
|
|
179
|
+
printf '%s\n\n%s\n%s\n' 'package com.tokamak.runtime' 'internal fun tokamakPlugins(app: TokamakApplication): List<TokamakPlugin> =' ' listOf(' > "$registry"
|
|
180
180
|
shopt -s nullglob
|
|
181
181
|
for plugin in "$input/plugins"/*/; do
|
|
182
182
|
plugin_id=$(basename "$plugin")
|
|
@@ -185,7 +185,7 @@ for plugin in "$input/plugins"/*/; do
|
|
|
185
185
|
echo "plugin '$plugin_id' has invalid android class '$class'" >&2
|
|
186
186
|
exit 1
|
|
187
187
|
fi
|
|
188
|
-
printf ' %s(host),\n' "$class" >> "$registry"
|
|
188
|
+
printf ' %s(app.host("%s")),\n' "$class" "$plugin_id" >> "$registry"
|
|
189
189
|
module=$plugin_modules/$plugin_id
|
|
190
190
|
mkdir -p "$module/src/main/kotlin"
|
|
191
191
|
for source in "$plugin/sources"/*; do
|
|
@@ -329,6 +329,7 @@ $(release_signing)
|
|
|
329
329
|
}
|
|
330
330
|
|
|
331
331
|
dependencies {
|
|
332
|
+
implementation 'androidx.lifecycle:lifecycle-process:2.11.0'
|
|
332
333
|
implementation 'androidx.webkit:webkit:1.12.1'
|
|
333
334
|
implementation project(':tokamak-plugin')
|
|
334
335
|
EOF
|
|
@@ -376,8 +377,13 @@ manifest=$app/src/main/AndroidManifest.xml
|
|
|
376
377
|
'</manifest>'
|
|
377
378
|
} > "$manifest"
|
|
378
379
|
|
|
379
|
-
# R8 keeps every name, so class names in errors and stack traces stay real
|
|
380
|
-
|
|
380
|
+
# R8 keeps every name, so class names in errors and stack traces stay real,
|
|
381
|
+
# and the methods the runtime calls from native code.
|
|
382
|
+
printf '%s\n' \
|
|
383
|
+
'-dontobfuscate' \
|
|
384
|
+
'-keep interface com.tokamak.runtime.TokamakRuntime$Plugins { *; }' \
|
|
385
|
+
'-keepclassmembers class * implements com.tokamak.runtime.TokamakRuntime$Plugins { *; }' \
|
|
386
|
+
> "$app/tokamak-rules.pro"
|
|
381
387
|
|
|
382
388
|
gradle --no-daemon "-Ptokamak.version=$version" ":app:lint$task" ":app:assemble$task" --project-dir "$project"
|
|
383
389
|
mkdir -p "$(dirname "$output")"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
[diffend] Oversized file quarantined before diffing.
|
|
2
2
|
name: package/android-arm64/lib/TokamakRuntime/libtokamak.a
|
|
3
|
-
size:
|
|
4
|
-
sha256:
|
|
3
|
+
size: 34943420 bytes
|
|
4
|
+
sha256: fb4b9ea1b76fd473b5b0f9c48f885e8a975f388d2a8ef634b8d530fb511bc9bb
|
|
@@ -5,22 +5,29 @@ import android.app.Application
|
|
|
5
5
|
import android.content.Context
|
|
6
6
|
import android.content.pm.PackageManager
|
|
7
7
|
import android.os.SystemClock
|
|
8
|
+
import android.util.Log
|
|
9
|
+
import androidx.lifecycle.DefaultLifecycleObserver
|
|
10
|
+
import androidx.lifecycle.LifecycleOwner
|
|
11
|
+
import androidx.lifecycle.ProcessLifecycleOwner
|
|
8
12
|
import java.io.File
|
|
13
|
+
import java.util.concurrent.Executors
|
|
14
|
+
import org.json.JSONTokener
|
|
9
15
|
|
|
10
16
|
private const val HOST_METADATA = "tokamak.host"
|
|
11
17
|
private const val DEV_ENDPOINT_METADATA = "tokamak.dev.endpoint"
|
|
12
18
|
private const val DEV_SESSION_TOKEN_METADATA = "tokamak.dev.session-token"
|
|
13
19
|
|
|
20
|
+
/** How long the Worker has for `resume` and `suspend`. */
|
|
21
|
+
private const val LIFECYCLE_DEADLINE_MILLIS = 10_000L
|
|
22
|
+
|
|
14
23
|
/**
|
|
15
24
|
* The tokamak process. Owns the runtime and native plugins, which outlive any activity, so a
|
|
16
25
|
* plugin can run Worker code when the system starts the app in the background.
|
|
17
26
|
*/
|
|
18
|
-
class TokamakApplication : Application(),
|
|
19
|
-
|
|
20
|
-
get() = this
|
|
21
|
-
|
|
27
|
+
class TokamakApplication : Application(), TokamakPlugins {
|
|
28
|
+
/** The app's activity, or null while it has none. */
|
|
22
29
|
@Volatile
|
|
23
|
-
|
|
30
|
+
var activity: Activity? = null
|
|
24
31
|
|
|
25
32
|
/** Every plugin, by ID. */
|
|
26
33
|
val plugins: Map<String, TokamakPlugin> by lazy {
|
|
@@ -33,34 +40,130 @@ class TokamakApplication : Application(), TokamakHost {
|
|
|
33
40
|
|
|
34
41
|
internal val permissionRequests = TokamakPermissions(this)
|
|
35
42
|
|
|
43
|
+
private val started = lazy(::startRuntime)
|
|
44
|
+
|
|
36
45
|
/** The running runtime, started on first use. Blocks while it starts. */
|
|
37
|
-
internal val runtime: TokamakRuntime by
|
|
46
|
+
internal val runtime: TokamakRuntime by started
|
|
47
|
+
|
|
48
|
+
/** Whether the app is in the foreground, as the lifecycle last reported. Main thread only. */
|
|
49
|
+
private var foreground = false
|
|
50
|
+
|
|
51
|
+
/** The Worker's calls and subscriptions on the plugins. Main thread only. */
|
|
52
|
+
private val workerRequests by lazy {
|
|
53
|
+
TokamakPluginRequests<Long>(plugins) { id, result -> runtime.reply(id, result.toString()) }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The plugins as the runtime calls them, on its own threads. */
|
|
57
|
+
private val workerPlugins =
|
|
58
|
+
object : TokamakRuntime.Plugins {
|
|
59
|
+
override fun call(id: Long, plugin: String, method: String, arguments: String) =
|
|
60
|
+
mainExecutor.execute { workerRequests.run(id, false, plugin, method, parse(arguments)) }
|
|
61
|
+
|
|
62
|
+
override fun subscribe(id: Long, plugin: String, method: String, arguments: String) =
|
|
63
|
+
mainExecutor.execute { workerRequests.run(id, true, plugin, method, parse(arguments)) }
|
|
64
|
+
|
|
65
|
+
override fun unsubscribe(id: Long) = mainExecutor.execute { workerRequests.cancel(id) }
|
|
66
|
+
|
|
67
|
+
private fun parse(arguments: String): Any? = JSONTokener(arguments).nextValue()
|
|
68
|
+
}
|
|
38
69
|
|
|
39
70
|
/** The host of the app origin, `https://<appHost>`. */
|
|
40
71
|
val appHost: String by lazy {
|
|
41
72
|
requireNotNull(metadata()?.getString(HOST_METADATA)) { "$HOST_METADATA is required" }
|
|
42
73
|
}
|
|
43
74
|
|
|
44
|
-
|
|
75
|
+
/** Delivers `resume` and `suspend` one at a time, in order. */
|
|
76
|
+
private val lifecycle = Executors.newSingleThreadExecutor()
|
|
77
|
+
|
|
78
|
+
override fun onCreate() {
|
|
79
|
+
super.onCreate()
|
|
80
|
+
ProcessLifecycleOwner.get().lifecycle.addObserver(
|
|
81
|
+
object : DefaultLifecycleObserver {
|
|
82
|
+
override fun onStart(owner: LifecycleOwner) = moved(foreground = true)
|
|
83
|
+
|
|
84
|
+
override fun onStop(owner: LifecycleOwner) = moved(foreground = false)
|
|
85
|
+
},
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
override fun plugin(id: String): TokamakPlugin? = plugins[id]
|
|
90
|
+
|
|
91
|
+
/** The host the plugin [id] sees, whose events the Worker's listeners receive as `<id>.<name>`. */
|
|
92
|
+
internal fun host(id: String): TokamakHost =
|
|
93
|
+
object : TokamakHost {
|
|
94
|
+
override val context: Context
|
|
95
|
+
get() = this@TokamakApplication
|
|
96
|
+
|
|
97
|
+
override val activity: Activity?
|
|
98
|
+
get() = this@TokamakApplication.activity
|
|
99
|
+
|
|
100
|
+
override val isInForeground: Boolean
|
|
101
|
+
get() = foreground
|
|
102
|
+
|
|
103
|
+
override fun requireForegroundActivity(): Activity =
|
|
104
|
+
this@TokamakApplication.requireForegroundActivity()
|
|
105
|
+
|
|
106
|
+
override fun wouldPrompt(permission: String): Boolean =
|
|
107
|
+
permissionRequests.wouldPrompt(permission)
|
|
108
|
+
|
|
109
|
+
override fun requestPermissions(
|
|
110
|
+
permissions: Set<String>,
|
|
111
|
+
callback: (Map<String, Boolean>) -> Unit,
|
|
112
|
+
) = permissionRequests.request(permissions, callback)
|
|
113
|
+
|
|
114
|
+
override fun emit(name: String, event: String, timeoutMillis: Long): String =
|
|
115
|
+
emitEvent("$id.$name", event, timeoutMillis)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The activity to show UI in; throws `NeedsUIError` while the app is in the background. */
|
|
119
|
+
internal fun requireForegroundActivity(): Activity =
|
|
120
|
+
activity?.takeIf { foreground } ?: throw TokamakPluginError.needsUI()
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Delivers the event [name] with the JSON [event] to the Worker's listeners and returns their
|
|
124
|
+
* reply as JSON. Starts the runtime when it is not running. Blocks.
|
|
125
|
+
*/
|
|
126
|
+
private fun emitEvent(name: String, event: String, timeoutMillis: Long): String {
|
|
45
127
|
val deadline = SystemClock.elapsedRealtime() + timeoutMillis
|
|
46
128
|
val started = runtime
|
|
47
|
-
return started.
|
|
129
|
+
return started.emit(name, event, deadline - SystemClock.elapsedRealtime())
|
|
48
130
|
}
|
|
49
131
|
|
|
50
|
-
|
|
132
|
+
/** Records the app moving into or out of the foreground, once the runtime has started. */
|
|
133
|
+
private fun moved(foreground: Boolean) {
|
|
134
|
+
this.foreground = foreground
|
|
135
|
+
if (started.isInitialized()) record(runtime)
|
|
136
|
+
}
|
|
51
137
|
|
|
52
|
-
|
|
53
|
-
|
|
138
|
+
/** Reports [foreground] to [runtime], delivering `resume` or `suspend` when it changed. */
|
|
139
|
+
private fun record(runtime: TokamakRuntime) {
|
|
140
|
+
if (!runtime.setForeground(foreground)) return
|
|
141
|
+
val name = if (foreground) "resume" else "suspend"
|
|
142
|
+
lifecycle.execute {
|
|
143
|
+
runCatching { runtime.emit(name, "{}", LIFECYCLE_DEADLINE_MILLIS) }
|
|
144
|
+
.onFailure { Log.w("tokamak", "tokamak $name failed", it) }
|
|
145
|
+
}
|
|
146
|
+
}
|
|
54
147
|
|
|
148
|
+
/**
|
|
149
|
+
* Starts the runtime, which delivers `start` in the foreground when an activity started it,
|
|
150
|
+
* then records where the app has moved since.
|
|
151
|
+
*/
|
|
55
152
|
private fun startRuntime(): TokamakRuntime {
|
|
56
153
|
val metadata = metadata()
|
|
57
154
|
val endpoint = metadata?.getString(DEV_ENDPOINT_METADATA)
|
|
58
155
|
val sessionToken = metadata?.getString(DEV_SESSION_TOKEN_METADATA)
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
156
|
+
val startsInForeground = activity != null
|
|
157
|
+
val runtime =
|
|
158
|
+
if (!endpoint.isNullOrEmpty() && !sessionToken.isNullOrEmpty()) {
|
|
159
|
+
TokamakRuntime.startDevelopment(
|
|
160
|
+
stateDir(), appHost, endpoint, sessionToken, startsInForeground, workerPlugins,
|
|
161
|
+
)
|
|
162
|
+
} else {
|
|
163
|
+
TokamakRuntime.start(unpackApp(), stateDir(), storageDir(), appHost, startsInForeground, workerPlugins)
|
|
164
|
+
}
|
|
165
|
+
mainExecutor.execute { record(runtime) }
|
|
166
|
+
return runtime
|
|
64
167
|
}
|
|
65
168
|
|
|
66
169
|
private fun metadata() =
|
|
@@ -1,27 +1,46 @@
|
|
|
1
1
|
package com.tokamak.runtime
|
|
2
2
|
|
|
3
|
+
import android.content.Context
|
|
3
4
|
import android.content.pm.PackageManager
|
|
4
5
|
|
|
6
|
+
private const val PREFERENCES = "tokamak.permissions"
|
|
7
|
+
private const val REFUSED = "refused"
|
|
8
|
+
|
|
5
9
|
/**
|
|
6
10
|
* Asks for runtime permissions in the app's activity one request at a time, as Android cancels a
|
|
7
|
-
* request made while another shows.
|
|
11
|
+
* request made while another shows. Remembers the permissions the user has refused for good, as
|
|
12
|
+
* Android reports them the same way as permissions never asked for. Use it on the main thread.
|
|
8
13
|
*/
|
|
9
|
-
internal class TokamakPermissions(private val
|
|
14
|
+
internal class TokamakPermissions(private val app: TokamakApplication) {
|
|
10
15
|
private class Request(val permissions: Set<String>, val callback: (Map<String, Boolean>) -> Unit)
|
|
11
16
|
|
|
12
17
|
private val queue = ArrayDeque<Request>()
|
|
18
|
+
private val preferences by lazy { app.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE) }
|
|
13
19
|
|
|
14
20
|
/** Identifies the request showing, the head of [queue]. */
|
|
15
21
|
private var requestCode = 0
|
|
16
22
|
|
|
23
|
+
/**
|
|
24
|
+
* Asks for [permissions], then passes [callback] whether each is granted. Answers at once when
|
|
25
|
+
* none would prompt; throws `NeedsUIError` when one would while the app is in the background.
|
|
26
|
+
*/
|
|
17
27
|
fun request(permissions: Set<String>, callback: (Map<String, Boolean>) -> Unit) {
|
|
18
|
-
|
|
28
|
+
val request = Request(permissions, callback)
|
|
29
|
+
if (permissions.none(::wouldPrompt)) return answer(request)
|
|
30
|
+
app.requireForegroundActivity()
|
|
31
|
+
queue.addLast(request)
|
|
19
32
|
if (queue.size == 1) askNext()
|
|
20
33
|
}
|
|
21
34
|
|
|
35
|
+
/** Whether asking for [permission] shows the system prompt. */
|
|
36
|
+
fun wouldPrompt(permission: String): Boolean =
|
|
37
|
+
!isGranted(permission) &&
|
|
38
|
+
(app.activity?.shouldShowRequestPermissionRationale(permission) == true || permission !in refused())
|
|
39
|
+
|
|
22
40
|
fun onRequestPermissionsResult(requestCode: Int) {
|
|
23
41
|
if (requestCode != this.requestCode || queue.isEmpty()) return
|
|
24
42
|
val answered = queue.removeFirst()
|
|
43
|
+
remember(answered.permissions)
|
|
25
44
|
askNext()
|
|
26
45
|
answer(answered)
|
|
27
46
|
}
|
|
@@ -36,14 +55,24 @@ internal class TokamakPermissions(private val host: TokamakHost) {
|
|
|
36
55
|
|
|
37
56
|
private fun askNext() {
|
|
38
57
|
val request = queue.firstOrNull() ?: return
|
|
39
|
-
val activity =
|
|
58
|
+
val activity = app.activity ?: return cancel()
|
|
40
59
|
requestCode += 1
|
|
41
60
|
activity.requestPermissions(request.permissions.toTypedArray(), requestCode)
|
|
42
61
|
}
|
|
43
62
|
|
|
63
|
+
/** Records which of the answered [permissions] the user refused for good. */
|
|
64
|
+
private fun remember(permissions: Set<String>) {
|
|
65
|
+
val activity = app.activity ?: return
|
|
66
|
+
val refusedForGood =
|
|
67
|
+
permissions.filter { !isGranted(it) && !activity.shouldShowRequestPermissionRationale(it) }
|
|
68
|
+
preferences.edit().putStringSet(REFUSED, refused() - permissions + refusedForGood).apply()
|
|
69
|
+
}
|
|
70
|
+
|
|
44
71
|
private fun answer(request: Request) =
|
|
45
72
|
request.callback(request.permissions.associateWith(::isGranted))
|
|
46
73
|
|
|
74
|
+
private fun refused(): Set<String> = preferences.getStringSet(REFUSED, null).orEmpty()
|
|
75
|
+
|
|
47
76
|
private fun isGranted(permission: String): Boolean =
|
|
48
|
-
|
|
77
|
+
app.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
|
|
49
78
|
}
|
|
@@ -12,12 +12,13 @@ import org.json.JSONObject
|
|
|
12
12
|
internal class TokamakPluginBridge(
|
|
13
13
|
private val activity: Activity,
|
|
14
14
|
private val host: String,
|
|
15
|
-
|
|
15
|
+
plugins: Map<String, TokamakPlugin>,
|
|
16
16
|
) : WebViewCompat.WebMessageListener {
|
|
17
17
|
private data class RequestKey(val session: String, val id: Int)
|
|
18
18
|
|
|
19
|
-
private val
|
|
19
|
+
private val requests = TokamakPluginRequests<RequestKey>(plugins, ::send)
|
|
20
20
|
private var activeSession: String? = null
|
|
21
|
+
private var replyProxy: JavaScriptReplyProxy? = null
|
|
21
22
|
|
|
22
23
|
fun install(webView: WebView) {
|
|
23
24
|
WebViewCompat.addWebMessageListener(
|
|
@@ -30,9 +31,8 @@ internal class TokamakPluginBridge(
|
|
|
30
31
|
|
|
31
32
|
fun close() {
|
|
32
33
|
activeSession = null
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
cancelAll.forEach { it() }
|
|
34
|
+
replyProxy = null
|
|
35
|
+
requests.cancelAll()
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
override fun onPostMessage(
|
|
@@ -50,79 +50,30 @@ internal class TokamakPluginBridge(
|
|
|
50
50
|
if (type == "reset") {
|
|
51
51
|
close()
|
|
52
52
|
activeSession = session
|
|
53
|
+
this.replyProxy = replyProxy
|
|
53
54
|
return
|
|
54
55
|
}
|
|
55
56
|
val id = request.optInt("id", -1)
|
|
56
57
|
if (id < 0) return
|
|
57
58
|
val key = RequestKey(session, id)
|
|
58
59
|
when (type) {
|
|
59
|
-
"cancel" ->
|
|
60
|
-
"call", "subscribe" ->
|
|
61
|
-
|
|
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"))
|
|
62
70
|
}
|
|
63
71
|
}
|
|
64
72
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
) {
|
|
71
|
-
val plugin = plugins[request.optString("plugin")]
|
|
72
|
-
val method = request.optString("method")
|
|
73
|
-
if (plugin == null || method.isEmpty()) {
|
|
74
|
-
sendNotSupported(replyProxy, key, "Plugin is not supported")
|
|
75
|
-
return
|
|
76
|
-
}
|
|
77
|
-
val arguments = request.opt("arguments")
|
|
78
|
-
val reply: TokamakPluginReply = { result -> send(replyProxy, key, result, isCall) }
|
|
79
|
-
try {
|
|
80
|
-
if (isCall) {
|
|
81
|
-
plugin.call(method, arguments, reply)
|
|
82
|
-
} else {
|
|
83
|
-
cancellations[key] = plugin.subscribe(method, arguments, reply)
|
|
84
|
-
}
|
|
85
|
-
} catch (error: Exception) {
|
|
86
|
-
send(replyProxy, key, Result.failure(error), true)
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
private fun sendNotSupported(
|
|
91
|
-
replyProxy: JavaScriptReplyProxy,
|
|
92
|
-
key: RequestKey,
|
|
93
|
-
message: String,
|
|
94
|
-
) = send(replyProxy, key, Result.failure(TokamakPluginError.notSupported(message)), true)
|
|
95
|
-
|
|
96
|
-
private fun send(
|
|
97
|
-
replyProxy: JavaScriptReplyProxy,
|
|
98
|
-
key: RequestKey,
|
|
99
|
-
result: Result<Any?>,
|
|
100
|
-
done: Boolean,
|
|
101
|
-
) = activity.runOnUiThread { deliver(replyProxy, key, result, done) }
|
|
102
|
-
|
|
103
|
-
private fun deliver(
|
|
104
|
-
replyProxy: JavaScriptReplyProxy,
|
|
105
|
-
key: RequestKey,
|
|
106
|
-
result: Result<Any?>,
|
|
107
|
-
done: Boolean,
|
|
108
|
-
) {
|
|
109
|
-
if (activeSession != key.session) return
|
|
110
|
-
val error = result.exceptionOrNull()
|
|
111
|
-
if (done) cancellations.remove(key)?.invoke()
|
|
112
|
-
val response =
|
|
113
|
-
JSONObject()
|
|
114
|
-
.put("session", key.session)
|
|
115
|
-
.put("id", key.id)
|
|
116
|
-
.put("done", done)
|
|
117
|
-
if (error == null) {
|
|
118
|
-
response.put("value", JSONObject.wrap(result.getOrNull()))
|
|
119
|
-
} else {
|
|
120
|
-
val name = (error as? TokamakPluginError)?.errorName ?: "OperationError"
|
|
121
|
-
response.put(
|
|
122
|
-
"error",
|
|
123
|
-
JSONObject().put("name", name).put("message", error.message ?: error.javaClass.name),
|
|
124
|
-
)
|
|
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())
|
|
125
78
|
}
|
|
126
|
-
replyProxy.postMessage(response.toString())
|
|
127
|
-
}
|
|
128
79
|
}
|
|
@@ -0,0 +1,57 @@
|
|
|
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
|
+
}
|
|
@@ -4,6 +4,19 @@ import java.io.File
|
|
|
4
4
|
|
|
5
5
|
/** The tokamak runtime, running for the life of the process. */
|
|
6
6
|
internal class TokamakRuntime private constructor(private val handle: Long) {
|
|
7
|
+
/**
|
|
8
|
+
* The app's plugins, which the Worker calls. The runtime calls these methods on its own
|
|
9
|
+
* threads, and each call or subscription is answered with [reply]: once for a call, and once
|
|
10
|
+
* per value for a subscription.
|
|
11
|
+
*/
|
|
12
|
+
interface Plugins {
|
|
13
|
+
fun call(id: Long, plugin: String, method: String, arguments: String)
|
|
14
|
+
|
|
15
|
+
fun subscribe(id: Long, plugin: String, method: String, arguments: String)
|
|
16
|
+
|
|
17
|
+
fun unsubscribe(id: Long)
|
|
18
|
+
}
|
|
19
|
+
|
|
7
20
|
/** The loopback port the gateway bound. */
|
|
8
21
|
val port: Int
|
|
9
22
|
get() = nativePort(handle)
|
|
@@ -11,11 +24,20 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
|
|
|
11
24
|
fun restoreGateway(): Int = nativeRestoreGateway(handle)
|
|
12
25
|
|
|
13
26
|
/**
|
|
14
|
-
*
|
|
15
|
-
*
|
|
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.
|
|
16
29
|
*/
|
|
17
|
-
fun
|
|
18
|
-
|
|
30
|
+
fun emit(name: String, event: String, timeoutMillis: Long): String =
|
|
31
|
+
nativeEmit(handle, name, event, timeoutMillis)
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Records whether the app is in the foreground, which the Worker's `getLifecycleStage()`
|
|
35
|
+
* reports from then on, and returns whether that changed.
|
|
36
|
+
*/
|
|
37
|
+
fun setForeground(foreground: Boolean): Boolean = nativeSetForeground(handle, foreground)
|
|
38
|
+
|
|
39
|
+
/** Passes a plugin's JSON [result] to the Worker's call or subscription [id]. */
|
|
40
|
+
fun reply(id: Long, result: String) = nativeReply(handle, id, result)
|
|
19
41
|
|
|
20
42
|
/**
|
|
21
43
|
* The authority a server certificate for [host] must chain to, or null
|
|
@@ -35,23 +57,37 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
|
|
|
35
57
|
System.loadLibrary("tokamak")
|
|
36
58
|
}
|
|
37
59
|
|
|
38
|
-
/**
|
|
60
|
+
/**
|
|
61
|
+
* Start the runtime, which delivers `start` with [foreground] and whose Worker calls
|
|
62
|
+
* [plugins], throwing when it cannot serve the app.
|
|
63
|
+
*/
|
|
39
64
|
fun start(
|
|
40
65
|
packagedDir: File,
|
|
41
66
|
stateDir: File,
|
|
42
67
|
storageDir: File,
|
|
43
68
|
host: String,
|
|
69
|
+
foreground: Boolean,
|
|
70
|
+
plugins: Plugins,
|
|
44
71
|
): TokamakRuntime =
|
|
45
|
-
TokamakRuntime(
|
|
46
|
-
|
|
47
|
-
|
|
72
|
+
TokamakRuntime(
|
|
73
|
+
nativeStart(packagedDir.path, stateDir.path, storageDir.path, host, foreground, plugins),
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Start the runtime against a host development server, delivering `start` with
|
|
78
|
+
* [foreground], whose development Worker calls [plugins].
|
|
79
|
+
*/
|
|
48
80
|
fun startDevelopment(
|
|
49
81
|
stateDir: File,
|
|
50
82
|
host: String,
|
|
51
83
|
endpoint: String,
|
|
52
84
|
sessionToken: String,
|
|
85
|
+
foreground: Boolean,
|
|
86
|
+
plugins: Plugins,
|
|
53
87
|
): TokamakRuntime =
|
|
54
|
-
TokamakRuntime(
|
|
88
|
+
TokamakRuntime(
|
|
89
|
+
nativeStartDevelopment(stateDir.path, host, endpoint, sessionToken, foreground, plugins),
|
|
90
|
+
)
|
|
55
91
|
|
|
56
92
|
@JvmStatic
|
|
57
93
|
private external fun nativeStart(
|
|
@@ -59,6 +95,8 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
|
|
|
59
95
|
stateDir: String,
|
|
60
96
|
storageDir: String,
|
|
61
97
|
host: String,
|
|
98
|
+
foreground: Boolean,
|
|
99
|
+
plugins: Plugins,
|
|
62
100
|
): Long
|
|
63
101
|
|
|
64
102
|
@JvmStatic
|
|
@@ -67,8 +105,16 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
|
|
|
67
105
|
host: String,
|
|
68
106
|
endpoint: String,
|
|
69
107
|
sessionToken: String,
|
|
108
|
+
foreground: Boolean,
|
|
109
|
+
plugins: Plugins,
|
|
70
110
|
): Long
|
|
71
111
|
|
|
112
|
+
@JvmStatic
|
|
113
|
+
private external fun nativeSetForeground(handle: Long, foreground: Boolean): Boolean
|
|
114
|
+
|
|
115
|
+
@JvmStatic
|
|
116
|
+
private external fun nativeReply(handle: Long, id: Long, result: String)
|
|
117
|
+
|
|
72
118
|
@JvmStatic
|
|
73
119
|
private external fun nativePort(handle: Long): Int
|
|
74
120
|
|
|
@@ -76,10 +122,10 @@ internal class TokamakRuntime private constructor(private val handle: Long) {
|
|
|
76
122
|
private external fun nativeRestoreGateway(handle: Long): Int
|
|
77
123
|
|
|
78
124
|
@JvmStatic
|
|
79
|
-
private external fun
|
|
125
|
+
private external fun nativeEmit(
|
|
80
126
|
handle: Long,
|
|
81
127
|
name: String,
|
|
82
|
-
|
|
128
|
+
event: String,
|
|
83
129
|
timeoutMillis: Long,
|
|
84
130
|
): String
|
|
85
131
|
|
|
@@ -13,7 +13,7 @@ private val RESOURCE_PERMISSIONS =
|
|
|
13
13
|
|
|
14
14
|
/** Grants the app origin's media capture requests once the app holds their permissions. */
|
|
15
15
|
internal class TokamakWebChromeClient(
|
|
16
|
-
private val tokamak:
|
|
16
|
+
private val tokamak: TokamakApplication,
|
|
17
17
|
private val host: String,
|
|
18
18
|
) : WebChromeClient() {
|
|
19
19
|
private val waiting = mutableSetOf<PermissionRequest>()
|
|
@@ -30,7 +30,12 @@ internal class TokamakWebChromeClient(
|
|
|
30
30
|
return
|
|
31
31
|
}
|
|
32
32
|
waiting += request
|
|
33
|
-
|
|
33
|
+
try {
|
|
34
|
+
tokamak.permissionRequests.request(missing.toSet()) { if (waiting.remove(request)) decide(request) }
|
|
35
|
+
} catch (_: TokamakPluginError) {
|
|
36
|
+
waiting -= request
|
|
37
|
+
request.deny()
|
|
38
|
+
}
|
|
34
39
|
}
|
|
35
40
|
|
|
36
41
|
override fun onPermissionRequestCanceled(request: PermissionRequest) {
|
|
@@ -45,5 +50,5 @@ internal class TokamakWebChromeClient(
|
|
|
45
50
|
request.resources.map(RESOURCE_PERMISSIONS::getValue).filterNot(::isGranted)
|
|
46
51
|
|
|
47
52
|
private fun isGranted(permission: String): Boolean =
|
|
48
|
-
tokamak.
|
|
53
|
+
tokamak.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
|
|
49
54
|
}
|
|
@@ -21,7 +21,8 @@ fun TokamakHost.requireOwnerAuthentication(authenticators: Int) {
|
|
|
21
21
|
/**
|
|
22
22
|
* Shows the system prompt, titled [title], for the device owner to authenticate with
|
|
23
23
|
* [authenticators], authorising [crypto] when given. Calls [succeeded] once they do; otherwise
|
|
24
|
-
* [reply] receives the failure.
|
|
24
|
+
* [reply] receives the failure. Throws `NeedsUIError` while the app is in the background. Call it
|
|
25
|
+
* on the main thread.
|
|
25
26
|
*/
|
|
26
27
|
fun TokamakHost.authenticateOwner(
|
|
27
28
|
title: CharSequence,
|
|
@@ -30,11 +31,7 @@ fun TokamakHost.authenticateOwner(
|
|
|
30
31
|
reply: TokamakPluginReply,
|
|
31
32
|
succeeded: () -> Unit,
|
|
32
33
|
) {
|
|
33
|
-
val activity =
|
|
34
|
-
activity ?: throw TokamakPluginError(
|
|
35
|
-
"InvalidStateError",
|
|
36
|
-
"The app has no activity to show the authentication prompt in",
|
|
37
|
-
)
|
|
34
|
+
val activity = requireForegroundActivity()
|
|
38
35
|
val builder = BiometricPrompt.Builder(activity).setTitle(title).setAllowedAuthenticators(authenticators)
|
|
39
36
|
if ((authenticators and Authenticators.DEVICE_CREDENTIAL) == 0) {
|
|
40
37
|
builder.setNegativeButton(activity.getString(android.R.string.cancel), activity.mainExecutor) { _, _ ->
|
|
@@ -16,6 +16,9 @@ class TokamakPluginError(
|
|
|
16
16
|
fun notSupported(message: String) = TokamakPluginError("NotSupportedError", message)
|
|
17
17
|
|
|
18
18
|
fun typeError(message: String) = TokamakPluginError("TypeError", message)
|
|
19
|
+
|
|
20
|
+
/** UI was needed while the app is in the background, where it cannot show any. */
|
|
21
|
+
fun needsUI() = TokamakPluginError("NeedsUIError", "The app cannot show UI while it is in the background")
|
|
19
22
|
}
|
|
20
23
|
}
|
|
21
24
|
|
|
@@ -45,7 +48,7 @@ interface TokamakPlugin {
|
|
|
45
48
|
fun onIntent(intent: Intent) = Unit
|
|
46
49
|
}
|
|
47
50
|
|
|
48
|
-
/** The app as
|
|
51
|
+
/** The app as one plugin sees it: its context, its activity, and its Worker. */
|
|
49
52
|
interface TokamakHost {
|
|
50
53
|
/** The application context. */
|
|
51
54
|
val context: Context
|
|
@@ -53,25 +56,43 @@ interface TokamakHost {
|
|
|
53
56
|
/** The app's activity, or null while it has none. */
|
|
54
57
|
val activity: Activity?
|
|
55
58
|
|
|
59
|
+
/** Whether the app is in the foreground, where it can show UI. Read it on the main thread. */
|
|
60
|
+
val isInForeground: Boolean
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The activity to show UI in. Throws `NeedsUIError` while the app is in the background, where
|
|
64
|
+
* it cannot show UI. Call it on the main thread.
|
|
65
|
+
*/
|
|
66
|
+
fun requireForegroundActivity(): Activity
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Whether asking for [permission] shows the system prompt: the app does not hold it, and the
|
|
70
|
+
* user has not refused it for good. Call it on the main thread.
|
|
71
|
+
*/
|
|
72
|
+
fun wouldPrompt(permission: String): Boolean
|
|
73
|
+
|
|
56
74
|
/**
|
|
57
75
|
* Asks the user for [permissions] in the app's activity once earlier requests finish, then
|
|
58
|
-
* passes [callback] whether each is granted.
|
|
76
|
+
* passes [callback] whether each is granted. Answers at once, without UI, when none would
|
|
77
|
+
* prompt; throws `NeedsUIError` when one would while the app is in the background. Call it on
|
|
59
78
|
* the main thread; [callback] runs on the main thread.
|
|
60
79
|
*/
|
|
61
80
|
fun requestPermissions(permissions: Set<String>, callback: (Map<String, Boolean>) -> Unit)
|
|
62
81
|
|
|
63
82
|
/**
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
* so call it off the main thread;
|
|
67
|
-
* [timeoutMillis], which includes runtime startup.
|
|
83
|
+
* 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.
|
|
68
87
|
*/
|
|
69
|
-
fun
|
|
88
|
+
fun emit(name: String, event: String, timeoutMillis: Long): String
|
|
89
|
+
}
|
|
70
90
|
|
|
91
|
+
/** The app's plugins. The app's [android.app.Application] is one. */
|
|
92
|
+
interface TokamakPlugins {
|
|
71
93
|
/** The plugin with [id], or null when the app does not include it. */
|
|
72
94
|
fun plugin(id: String): TokamakPlugin?
|
|
73
95
|
}
|
|
74
96
|
|
|
75
|
-
/** The
|
|
76
|
-
|
|
77
|
-
get() = applicationContext as TokamakHost
|
|
97
|
+
/** The plugin with [id] in the app this context belongs to, or null when the app does not include it. */
|
|
98
|
+
fun Context.tokamakPlugin(id: String): TokamakPlugin? = (applicationContext as TokamakPlugins).plugin(id)
|